Wikidata talk:SPARQL query service/queries/examples

From Wikidata
Jump to navigation Jump to search

Page creation

[edit]

I have moved the examples from https://www.mediawiki.org/wiki/Wikibase/Indexing/SPARQL_Query_Examples to here. I will change query.wikidata.org to load the examples from here within the next weeks. Please help to maintain this list of query examples!

Thanks, --Jonas Kress (WMDE) (talk) 19:01, 17 July 2016 (UTC)[reply]

@Smalyshev (WMF):: I like the new template, but it seems to fail for the samples at the end of the page. Supposedly because of the limit of 500.
--- Jura 21:42, 19 September 2016 (UTC)[reply]
@Jura1: Not sure why we've got fails in SPARQL2, that didn't happen before. Maybe something changed since last time I checked. --Smalyshev (WMF) (talk) 22:01, 19 September 2016 (UTC)[reply]
Oh of course, somebody added using Q template there. Which uses expensive functions. Adding widgets is nice but I'll have to roll it back. --Smalyshev (WMF) (talk) 22:07, 19 September 2016 (UTC)[reply]
It still fails. Given the help offered by Lea [1], maybe she can do something about the 500 limit @Lea Lacroix (WMDE):.
--- Jura 11:03, 20 September 2016 (UTC)[reply]
@Jura1: Seems to be fine now. --Smalyshev (WMF) (talk) 19:43, 21 September 2016 (UTC)[reply]
Looks good. Did you do something or is just my screen?
--- Jura 20:56, 21 September 2016 (UTC)[reply]
I fixed the templates and converted a bunch of them to SPARQL2 (which should be used from now on). --Smalyshev (WMF) (talk) 19:28, 22 September 2016 (UTC)[reply]
Good. BTW, the wordcloud on WQS doesn't seem to take input from the module.
--- Jura 00:06, 26 September 2016 (UTC)[reply]
@Smalyshev (WMF):
--- Jura 19:28, 28 September 2016 (UTC)[reply]
@Jura1: Example of missing things would help. --Smalyshev (WMF) (talk) 19:32, 28 September 2016 (UTC)[reply]
@Smalyshev (WMF): "cat"? I think it's easier to check what's there and then go to the sample and look at the source text. You will noticed that they all use the old format.
--- Jura 19:37, 28 September 2016 (UTC)[reply]
@Jura1: I have a feeling I didn't understand your question. I type "cat" in filter in query examples and it shows me the cats queries. Looks like you're talking about something else. So maybe it'd be better to do it this way: please describe, in maximum possible detail, 1) what you were doing 2) which result you expected to see 3) which result you observed instead and how it is different from the result you expected (unless its obvious). Or submit a bug report on phabricator, that'd work too :) --Smalyshev (WMF) (talk) 19:48, 28 September 2016 (UTC)[reply]

@Smalyshev (WMF): It's about the wordcloud above the filter. "cat" should appear there (or at least more than the ones that are visible now). All words in that cloud seem to be from samples using the old format. Click "pope (Q19564)" and look at the three queries starting Wikidata:SPARQL_query_service/queries/examples#List_of_popes. If you type "cat" in the filter, you get section headers (that works).
--- Jura 19:57, 28 September 2016 (UTC)[reply]

OK, I see what you mean now, will check it. --Smalyshev (WMF) (talk) 22:45, 6 October 2016 (UTC)[reply]
@Jura1: @Smalyshev (WMF): Should we convert all examples to sparql2 template? --Jonas Kress (WMDE) (talk) 19:53, 7 October 2016 (UTC)[reply]
@Jonas Kress (WMDE): see discussion here: https://www.wikidata.org/w/index.php?title=Topic:Tcxv4rdaqcpa1f2q&topic_showPostId=tcyp5r1n22868jtu&fromnotif=1#flow-post-tcyp5r1n22868jtu there may be some issues with that, need closer look. --Smalyshev (WMF) (talk) 19:56, 7 October 2016 (UTC)[reply]
@Smalyshev (WMF): What is the current status with migrating to SPARQL2 template? --Jonas Kress (WMDE) (talk) 08:15, 22 May 2017 (UTC)[reply]
Haven't had much time to look into it, so same as before I imagine... :\. Probably needs somebody to look into it, but I'm pretty busy so far, maybe in a couple of weeks... --Smalyshev (WMF) (talk) 18:50, 23 May 2017 (UTC)[reply]

Splitting ?

[edit]

The page is becoming quite heavy. What about a split ? author  TomT0m / talk page 18:32, 25 September 2016 (UTC)[reply]

Examples are a good way to learn SPARQL, but not the only way. There are things you can´t learn this way. For example, I would like to understand how to use RDF_Dump_Format#Ontology. One problem I have never understand, when do I have to use wdt:P123, p:P123, pr:P123, etc. So far I´m looking for an example and then I´m adapting that example to what I want. We should rather have next to the examples a textbook for SPARQL. --Molarus 00:03, 26 September 2016 (UTC)[reply]

Translation

[edit]

@Jonas Kress (WMDE), Smalyshev (WMF): How to translate all this without breaking the parser that import all of this into wdqs ? I notice that the query service itself is not translated, but it should be possible to parse the resulting page for each language and feed this into translations for wdqs in all those languages. author  TomT0m / talk page 11:15, 15 October 2016 (UTC)[reply]

@TomT0m: WDQS scrapes the html content of this page, so when this page is translated we could show it in WDQS. --Jonas Kress (WMDE) (talk) 12:27, 15 October 2016 (UTC)[reply]
Thanks, so no problems translating it. I'll put the "translate" tags. author  TomT0m / talk page 12:30, 15 October 2016 (UTC)[reply]
And than everything was broken. I reverted all the translate stuff. Please first test in some sandbox first before doing a next try. Why do we want to add translations to this page anyway? It makes the source unreadable. Multichill (talk) 19:53, 16 October 2016 (UTC)[reply]
@Multichill: My guess is that very few people read the source compared to the person who have to read the examples. OK, putting tags makes the stuff sighty less readable but one of the next WMF move is to modernize the texteditor and has been visual editor. Please ask themselves to take care of the translate extension to remove the burden ;) This is the best way to deal with stuff. Not to refuse translations ... author  TomT0m / talk page 06:23, 17 October 2016 (UTC)[reply]
Another note: loading revision with translate tags[2] takes 26 seconds, loading revision without translate tags[3] takes 7 seconds. For whatever reason parser cache did not work there (or was invalidated too often) when revision with translate tags was the latest one. It was very annoying. --Lockal (talk) 07:29, 17 October 2016 (UTC)[reply]
Seven seconds is already way too long imho. But I'll post a butreport on translation extension phabricator to understand if there is no performance issue with this. But somethinh that might invalidate the cache, I don't know how the page is coded, is that some templates like {{Query labels}} uses {{Int:lang}} ... so the page depends of the language of the reader. author  TomT0m / talk page 16:45, 17 October 2016 (UTC)[reply]
Wouldn't it be the best to first request translations for https://query.wikidata.org? --Pasleim (talk) 08:14, 17 October 2016 (UTC)[reply]
@Pasleim: My understanding is that this page is used as standalone example provider as well if people are annoyed by the loading time so transate all of this might be useful for non-english speakers as well here. author  TomT0m / talk page 16:45, 17 October 2016 (UTC)[reply]

Map a list of IDs to the corresponding values for other properties

[edit]

It would be good to have an example query which does what toollabs:wikidata-todo/multibeacon.php does (or used to do). --Nemo 10:22, 5 December 2016 (UTC)[reply]

Query involving elevation above sea level (P2044)

[edit]

The SPARQL example query Italian mountains higher than 4000 m seems to return results of mountains with elevation higher than 4000 feet. Does anyone know a proper way to rephrase this query, to get only the correct results? --Zhenqinli (talk) 03:11, 10 March 2017 (UTC)[reply]

I looks like results for this query are all in meters at this moment, but I updated it anyway to use normalized values. --Lockal (talk) 10:55, 16 March 2017 (UTC)[reply]
[edit]

It was a little hard to find. Would be nice to have an 'edit' button on the top of the examples list that directed the user to here. --I9606 (talk) 20:09, 15 March 2017 (UTC)[reply]

Suggestion of an improvement in the "Recent events" query

[edit]

The Recent events query currently uses the following syntax:

# with a point in time or start date
OPTIONAL { ?event wdt:P585 ?date. }
OPTIONAL { ?event wdt:P580 ?date. }
# but at least one of those
FILTER(BOUND(?date) && DATATYPE(?date) = xsd:dateTime).

but that sounds a bit weird to me to use "OPTIONAL" for something that isn't actually optional. Why don't we do something like this?

# with a point in time or start date
?event (wdt:P585 | wdt:P580) ?date.
FILTER(DATATYPE(?date) = xsd:dateTime).

Or with a "UNION" if you prefer? It gives the same results and looks cleaner. − Pintoch (talk) 20:12, 27 March 2017 (UTC)[reply]

Categorize queries by SPARQL functions too

[edit]

I would be nice if the search would also work for examples that use certain functions / methods. So searching BIND, IF, FILTER, etc.. should all yield a few good example queries. --Tobias1984 (talk) 19:22, 25 April 2017 (UTC)[reply]

Add example for IF EXISTS

[edit]

I think currently there is no example showing how IF EXISTS works. I made this one today: --Tobias1984 (talk) 19:27, 25 April 2017 (UTC)[reply]

# Castles and mountains: Shows how BIND IF construct works. See if castles are close to mountains (a source of castle building material)
SELECT ?item ?itemLabel ?coord ?layer
WHERE
{
    {
        ?item wdt:P31 wd:Q8502 .
    }
    UNION 
    {
        ?item wdt:P31 wd:Q23413 .
    }
  
    ?item wdt:P625 ?coord .
  
    BIND(
    	IF(EXISTS {?item wdt:P31 wd:Q8502}, "Mountain",
    	IF(EXISTS {?item wdt:P31 wd:Q23413}, "Castle",
           "Unknown"))
    AS ?layer)

	SERVICE wikibase:label { bd:serviceParam wikibase:language "en" }
}
Try it!

Federated queries examples?

[edit]

Hello, I have already posted this request on Wikidata talk:SPARQL federation input but maybe is it more relevant on this page. According to Wikidata:SPARQL federation input/Archive some other endpoints can be federated with wikidata's endpoint. I think it would be great to have a least on example showing how to take advantage of this option. I am not knowledgeable enough myself to write the query, sorry:) Symac (talk) 06:48, 17 May 2017 (UTC)[reply]

Example with deprecated ranks

[edit]

There should be added a more concrete example of work with statements with deprecated ranks and their combination with non-deprecated ones. The only one example query it's not explained/described and it doesn't speak for itself. Unexperinced users probably will have troubles trying to fork it into a working example of concrete query. --XXN, 23:08, 28 May 2017 (UTC)[reply]

Wikisource and Commons

[edit]

Hello. I can't see any example with Wikisource links or Commons. Can you provide one example? Thank you. Emijrp (talk) 06:16, 9 June 2017 (UTC)[reply]

Translate the name of queries

[edit]

Hello,

We made a few tests and we can now make this page translatable, at least the name of the queries (entered in the different levels of heading). This would allow to have translated queries names in the query service, depending on the user interface language.

This can't be done inside the query itself though, for example to translate the comments.

What do you think? If now one opposes, I can add the code to allow translation of the titles. Lea Lacroix (WMDE) (talk) 13:32, 30 June 2017 (UTC)[reply]

What needs to be done to make this happen? Add <translate> tags (I tried to do this in User:Lucas Werkmeister (WMDE)/Translated query examples) and then have an admin mark it for translation? Or is something else necessary? --Lucas Werkmeister (WMDE) (talk) 13:09, 20 July 2017 (UTC)[reply]
@Lea Lacroix (WMDE): Okay, I’ve added <translate> tags with the following command:
xclip -o | sed 's|^\(=\+\)[[:space:]]*\(.*\)[[:space:]]*\1|\1 <translate>\2</translate> \1|' | sed 's| </translate>|</translate>|' | xclip
Anything left to do? Apparently a translation admin still needs to mark the changes for translation. --Lucas Werkmeister (WMDE) (talk) 10:46, 2 August 2017 (UTC)[reply]
I am a translation admin :D It's done, now ready for being translated in all the languages! Lea Lacroix (WMDE) (talk) 10:51, 2 August 2017 (UTC)[reply]
Convenient :D thanks! --Lucas Werkmeister (WMDE) (talk) 15:03, 2 August 2017 (UTC)[reply]

✓ Done

Too many templates

[edit]

The page is not rendered correctly as it have too many inclusions. I'm not sure how it will affect query.wikidata.org but there are two possible soluitions:

Eran (talk) 05:47, 7 July 2017 (UTC)[reply]

CC0?

[edit]

Perhaps we should try to put the queries under a CCO license? --Marsupium (talk) 15:18, 12 July 2017 (UTC)[reply]

wikibase:api

[edit]

Please, add examples using "wikibase:api", for example how to retrieve newpages. Emijrp (talk) 11:29, 26 July 2017 (UTC)[reply]

Bug in query for Yearly Population stacked by country

[edit]

The query adds several population statistics for the same country and the same year.

See for example for the Republic of China: 2010 population - 4.0 billion (there is no single statement in the item with this figure).

tinyurl.com/ycfotduk

-- Beat Estermann (talk) 10:55, 12 October 2017 (UTC)[reply]

This has been a mistake in People's Republic of China (Q148), because male, female and total population were entered as separate property statements. If you look at Czech Republic (Q213) female and male population should be entered as qualifying statements female population (P1539), male population (P1540) to the total pop. statement. Fixed. --84.133.106.91 12:45, 9 November 2017 (UTC)[reply]
After having fixed the mistake, there were still multiple valid values that might have been counted twice or more often. This is fixed now for sure (result and query were checked while iterating on year 2010 data - if you still find a mistake in the result set for other years, please give, yet again, feedback). Thanks. --Cmuelle8 (talk) 13:22, 10 November 2017 (UTC)[reply]

Really needs an overhaul

[edit]

This list of examples is proposed by the Wikidata sparql enginge, but I have found it hard to use for building my own queries. It is very long with loads and loads of redundant examples. I think we should start by listing the various Sparql capabilities we want to document, and then provide one or two general-knowledge examples for each of them. Lengthy list of queries by topic do not serve much topic when queries are so easily transposable from one topic to another. --Zolo (talk) 18:51, 4 February 2018 (UTC)[reply]

Yes, this is important because there are so many queries the template limit has been set, meaning that queries at the end of the page weren't displaying. I've removed a few queries that are near-duplicates. User:CalvinBall, you've recently added a section headed "Europeana" where the queries don't seem specific to Europeana (they don't use the Europeana syndicated SPARQL, for example). Can these queries be moved to a dedicated project page, or alternatively moved to fit with the structure of the rest of the page? MartinPoulter (talk) 09:26, 16 June 2018 (UTC)[reply]
hi MartinPoulter, I think it would be best if the queries currently under the Europeana heading would be put into the current structure of the page. We created that subheading for a wikidata workshop at Europeana in May, but I agree it doesn't really warrant preserving. I'll integrate the queries into the rest of the page. CalvinBall (talk) 08:41, 19 June 2018 (UTC)[reply]

Request for example for showing all items which have a property

[edit]

Hi all

It would be really helpful to have an example query that would show all items which had a property. This will be useful for all items which appear and an external catalogue.

Thanks

John Cummings (talk) 11:11, 8 June 2018 (UTC)[reply]

John, if you want all items which have a given type of identifier, it can be as easy as:
SELECT ?item WHERE {
?item wdt:P1802 [] # Every item with an EMLO Person ID
}
Try it!

MartinPoulter (talk) 08:57, 16 June 2018 (UTC)[reply]

Thanks very much @MartinPoulter:. --John Cummings (talk) 18:10, 20 June 2018 (UTC)[reply]

Creating map images based on queries

[edit]

I'm curious, is there an easy way to generate map images on Wikimedia Commons based on query results, such as the U.S. newspaper query recently created by @99of9:? I'd like to create state-based maps for WikiProject. Is there an easier/better way to do it than making a screenshot and manually uploading it? -Pete F (talk) 17:50, 12 August 2018 (UTC)[reply]

Statements originating from a specific DOI

[edit]

Wikidata:SPARQL_query_service/queries/examples#Statements_originating_from_a_specific_DOI This query currently gives no results. Is there a better DOI that can be used as an example? MartinPoulter (talk) 14:08, 16 August 2018 (UTC)[reply]

@MartinPoulter: I fixed the example (DOIs on Wikidata are uppercase). You can get more examples via queries like this one, which also counts the number of statements supported by that particular source:
SELECT DISTINCT ?item ?doi (COUNT(DISTINCT ?statement) AS ?count)
WHERE { 
    ?statement prov:wasDerivedFrom/pr:P248 ?item .
    ?item wdt:P50 ?author ;
          wdt:P932 [] ;
          wdt:P356 ?doi ;
          wdt:P921 [].
    ?author wdt:P21 wd:Q6581072 ;
            wdt:P496 ?orcid .
    [] wdt:P2860 ?item .
    
}
GROUP BY ?item ?doi
HAVING (?count > 10)
ORDER BY DESC(?count)
Try it!
This query is tuned for papers that have a full Scholia profile in the "works" aspect, which has a "Supports the following statement(s)" panel (example)--Daniel Mietchen (talk) 22:10, 17 August 2018 (UTC)[reply]

Exclude items with time qualifier before timestamp

[edit]

I couldn't find an example with a date comparison for the (optional) *qualifier* of a statement, like "end date" (P582), although there are some related examples. If this example is useful for someone else, please include it:

SELECT ?item ?end WHERE {
  ?item wdt:P131* wd:Q3622022 . 
  ?item wdt:P2186 ?wlmid .
  MINUS { ?item p:P2186 [ pq:P582 ?end ] .
  FILTER ( ?end <= "2018-09-01T00:00:00+00:00"^^xsd:dateTime ) }
}

--Nemo 13:55, 25 August 2018 (UTC)[reply]

Template transclusion not working all the way down to the bottom of the page

[edit]

At some point within the "Queries for maintenance" section, queries are not shown any more, but only a "Template:SPARQL" link (linking to the template) is displayed. I've tried this with a current Firefox and Chrome (with the latter, I once saw the full list of queries once, but not again).

Perhaps it would be a good idea anyway to split out the maintenance and unsorted queries to a spearate page. (Even if they are not visible any more in the help menu.) Jneubert (talk) 16:46, 8 November 2018 (UTC)[reply]

Cashed results

[edit]

It seems it takes sometime for the SPARQL to update the results when WD is modified. Is there any documentation on this (in particular the time it takes to refresh). Mahdimoqri (talk) 15:44, 18 November 2018 (UTC)[reply]

Vermeer

[edit]

Hi @Husky:, could you please update your sparql with the current location of the paintings ? For instance, A Young Woman Seated at the Virginals (Q4660880) should be shown here Hermitage Museum (Q132783) for the time being. Thanks ! Bouzinac (talk) 15:34, 4 December 2018 (UTC)[reply]

"OR"

[edit]

I created this request to find recently died comics artist (Q715301) and subclasses.

I'd like to expand this request to all recently died comics artist (Q715301) OR cartoonist (Q1114448) and their subclasses but I can't find how to do this (I tried with « UNION » and « || »).

Could anyone help me ? Thanks. Kokonino (talk) 08:06, 13 January 2019 (UTC)[reply]

@Kokonino: The syntax for UNION would be {?item (wdt:P106/wdt:P279*) wd:Q715301} UNION {?item (wdt:P106/wdt:P279*) wd:Q1114448} -- Luitzen (talk) 22:21, 21 March 2019 (UTC)[reply]
@Luitzen: thank you so much ; now you write it, it seems obvious Kokonino (talk) 23:42, 21 March 2019 (UTC)[reply]

Update query

[edit]

Hello, is it possible to update this query shown in example list ([[4]] with better filters ?

PREFIX geof: <http://www.opengis.net/def/geosparql/function/>
#added before 2016-10
#defaultView:Map
SELECT ?place ?placeLabel (SAMPLE(?location) as ?localisation) WHERE {
  wd:Q933 wdt:P625 ?southPole.
  ?place wdt:P30 wd:Q51.
  ?place wdt:P625 ?location.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
  MINUS { ?place wdt:P576 _:b4. }
  MINUS { ?place wdt:P582 _:b5. }
  FILTER((geof:distance(?location, ?southPole)) > 3000)
}
group by ?place ?placeLabel
Try it!

Bouzinac (talk) 14:53, 16 January 2019 (UTC)[reply]

A kind of test

[edit]

https://paws-public.wmflabs.org/paws-public/User:Luitzen/Query%20examples%202.ipynb, scroll down to results. -- Luitzen (talk) 22:59, 19 March 2019 (UTC)[reply]

WITH ... AS ...

[edit]

Does anybody know where to get information about the "WITH ... AS %var_name" construct? I hardly find anything online, but it works with the endpoint. I am trying to use two WITHs between the same "SELECT...WHERE", but am having no luck. Thanks! Pdehaye (talk) 14:59, 10 May 2019 (UTC)[reply]

Hi, @Pdehaye! Have you found it? I'm on the similar WITH ... AS %var ... INCLUDES %var search path. Flipping Switches (talk) 21:16, 21 December 2023 (UTC)[reply]
There it is. Flipping Switches (talk) 12:42, 28 January 2024 (UTC)[reply]

Coloring of edges in graph views

[edit]

Is there any way to color an edge independently of the colors of the nodes?

For example, is there any way to get black edges here?


#added before 2016-10
#defaultView:Graph
SELECT DISTINCT ?item ?itemLabel ?rgb ?link
WHERE
{
  VALUES ?toggle { true false }
  ?disease wdt:P699 ?doid;
           wdt:P279+ wd:Q18123741;
           wdt:P2176 ?drug.
  ?drug rdfs:label ?drugLabel.
		FILTER(LANG(?drugLabel) = "en").
  ?disease rdfs:label ?diseaseLabel.
		FILTER(LANG(?diseaseLabel) = "en").
  BIND(IF(?toggle,?disease,?drug) AS ?item).
  BIND(IF(?toggle,?diseaseLabel,?drugLabel) AS ?itemLabel).
  BIND(IF(?toggle,"FFA500","7FFF00") AS ?rgb).
  BIND(IF(?toggle,"",?disease) AS ?link).
}
Try it!

I am asking because in my example I would go through 3 types of nodes (A, B, C), with 6 types of edges (A-B, B-C, A-C), and would like to be able to finely color things. Thanks! Pdehaye (talk) 00:31, 11 May 2019 (UTC)[reply]

Complex objects through values

[edit]

The following is nonsensical but works:

#
SELECT ?a ?b ?c WHERE
{
  VALUES (?a ?c) {
    (wd:Q41 wd:Q50)
    (wd:Q46 wd:Q47)
  }.
  VALUES ?b {wd:Q43 wd:Q44}.
}
Try it!

It allows to select as values some pairs. It would be good to use this in an example. One possibility I see is for a graphview with multiple node types, colored differently (the colors are assigned through this "values"). Pdehaye (talk) 06:53, 21 May 2019 (UTC)[reply]

Tree / Continents, countries, regions and capitals - example is not valid

[edit]

Continents, countries, regions and capitals example doesn't seem to be valid. While it shows cities sometimes, most frequently it displays a mess of regions and cities, and no cities inside regions. You can see it in every other European country, Russia or USA. It needs to be rewritten (if it's possible at all).

Scholarly articles with "Zika" in the item label

[edit]

This query gives a timeout error. Or am I doing something wrong? Keren - WMIL (talk) 10:27, 25 June 2019 (UTC)[reply]

Error in query service

[edit]

The query "Canadian subjects with no English article in Wikipedia" does not display correctly in the Query Service. It only contains the lines

SELECT ?item ?itemLabel ?cnt WHERE {
{
  SELECT ?item (COUNT(?sitelink) AS ?cnt) WHERE { 
  ?item wdt:P27
Try it!

so everything after the first pipe is omitted. Pipes in other queries do not have this problem. Steak (talk) 08:54, 9 September 2019 (UTC)[reply]

Changes to Wikidata Query Service UI’s example loading

[edit]

Hello all,

We recently made some changes to the way the Wikidata Query Service UI loads the example queries. This change can impact people who are maintaining these queries, as well as people running their own Wikibase instance including the Query Service.

Before the change, our approach was to get the HTML of that wiki page from Parsoid (this includes some template metadata which the normal parser output doesn’t include), and from that extract the query parameter of all {{SPARQL}} and {{SPARQL2}} transclusions.

With our improved approach, we get the HTML of that wiki page from the parser, and from that extract the contents of all syntax highlighted blocks.

The improvements resulting from this change are the following:

  • The queries no longer have to be specified directly on the page using {{SPARQL}} or {{SPARQL2}}; they can be transcluded indirectly, e. g. using {{Query page}}. You can see a comparison at User:TweetsFactsAndQueries/Queries-test-transclude and User:TweetsFactsAndQueries/Queries-test-copy. If we go with the solution of one query per page, we should be aware that we can fit less queries on the examples page before we hit some parser limits. Maybe now is a good time to sort and tidy the list of examples? :)
  • Queries that contained an unescaped pipe character (|) were previously cut off at that character in the query service UI, this should now be fixed and all queries should be displayed just like on the wikipage.
  • If the examples page hits some limit of the parser, then some examples will not be loaded, whereas with the previous approach they would still be loaded and shown on the query service UI even though they weren’t working correctly on the wiki page.

If you encounter any issues with the examples page, please let us know by adding a comment at under this task. Thanks, Lea Lacroix (WMDE) (talk) 15:36, 4 December 2019 (UTC)[reply]

Some more technical details on the parser limits, to inform the “one big page vs. one page per query” decision. The relevant limit is the “post-expand include size”, which is incremented each time the parser replaces a template with its expansion. You can see the limit by looking at the source code of a page (Ctrl+U, then search for “include size”) – on User:TweetsFactsAndQueries/Queries-test-transclude, it’s 40178/2097152 bytes, whereas on User:TweetsFactsAndQueries/Queries-test-copy it’s 23638/2097152 bytes (currently). So transcluding the queries, rather than copy+pasting them, costs you almost twice as much of that limit – I think that’s because with the {{Query page}} version, the entire query text ends up being transcluded twice (once into {{Query page}}, once into {{SPARQL}}), and so it’s counted against the limit twice.
The examples page was affected by this limit until recently, by the way: in this revision, the last 28 examples were plain links to Template:SPARQL because the limit had been reached. However, So9q then split up the examples page so that it no longer hits this limit, and currently all examples are loaded correctly again (but only those that were not split off into separate pages). --Lucas Werkmeister (WMDE) (talk) 15:56, 4 December 2019 (UTC)[reply]

Example doesn't work

[edit]

FYI, the example given in section "Map of places mentioned in travel stories with text in French accessible online" doesn't yield any result. Wikidata:SPARQL_query_service/queries/examples#Map_of_places_mentioned_in_travel_stories_with_text_in_French_accessible_online --Kimdime (talk) 17:33, 14 December 2019 (UTC)[reply]

Articles of a category without Wikidata items

[edit]

Please help me with the request. --Vladis13 (talk) 23:54, 1 March 2020 (UTC)[reply]

@Vladis13: I can understand that you are requesting an query like articles or/and category which are not connected with Wikidata items from "xyz" wiki. Could you please clear your request and which wiki, articles or/and category! Thanks! Regards, ZI Jony (Talk) 12:07, 2 March 2020 (UTC)[reply]
Thanks for reply. I want a list of articles of https://ru.wikisource.org/wiki/Category:%D0%AD%D0%A1%D0%93 (ru "ЭСГ") which have not WD items. It is better if the request will be able to specify several categories, since the request is needed for a bot. E.g. + https://ru.wikisource.org/wiki/Category:%D0%93%D0%A1%D0%A1:%D0%94%D0%9E (ru "ГСС:ДО") --Vladis13 (talk) 19:17, 2 March 2020 (UTC)[reply]

Largest cities with mayors who identify as female

[edit]

This was one of my favorite queries to share and teach with. I'm not sure why it disappeared. If anyone is looking for it, you can find it here: https://w.wiki/3Bb. Cheers. Will (Wiki Ed) (talk) 16:40, 6 April 2020 (UTC)[reply]

It was moved to Wikidata:SPARQL query service/queries/examples/advanced. --Lockal (talk) 09:50, 19 August 2020 (UTC)[reply]

error in example query Public_art_in_Paris

[edit]

Wikidata:SPARQL_query_service/queries/examples#Public_art_in_Paris yields error. --Herzi Pinki (talk) 16:03, 19 April 2020 (UTC)[reply]

Pls. correct "Places with continent Antarctica more than 3000?km north of south pole"

[edit]

In the title and in the query, there are two wrong "?" characters in "3000?km". Pls. correct. --Wikinaut (talk) 13:09, 9 May 2020 (UTC)[reply]

The Doctor Who example is wrong, I think

[edit]

Instead of looking for instance of "The Doctor" (Q34358), it should be looking for instance of "Regeneration of The Doctor" (Q47543030).

Jedieaston (talk) 15:56, 8 July 2020 (UTC)[reply]

✓ Done I also changed the triple for performer from best rank to all ranks, because the title says "all". --Dipsacus fullonum (talk) 18:39, 8 July 2020 (UTC)[reply]

The output of "The Simpsons series episodes list by season" example is incorrect

[edit]

The current query seems not working showing 0 results. The proper and easier way to fix it is this:

SELECT ?show ?showLabel ?seasonNumber ?episode ?episodeLabel
WHERE {
  BIND(wd:Q886 as ?show) .
  ?season wdt:P361 ?show;
          wdt:P527 ?episode;
          p:P179 [pq:P1545 ?seasonNumber] .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
} 
ORDER BY xsd:integer(?seasonNumber)
Try it!
Applied to the article. Thank you! --Nuretok (talk) 10:43, 2 July 2022 (UTC)[reply]

Proposition of a new example

[edit]

Dear all, for some reason I cannot edit the main page. If the community thinks it is a good example, would someone please edit the main page (or the page about advanced examples, but this page doesn't update the list on the wdqs). Basically, I wanted to run a query using an external property equivalent to a wikidata property. Here is such a query using the property from the rda registry http://rdaregistry.info/Elements/u/P60697 matching with P463 (is member of)

#Running a query using an external property equivalent to a wikidata property. Here things member of (P463) other things
SELECT ?tout ?toutLabel ?membre ?membreLabel 
WHERE 
{?propwikibase wdt:P1628 <http://rdaregistry.info/Elements/u/P60697>.
   ?propwikibase wikibase:directClaim ?propwikibasedirectclaim.
  ?tout ?propwikibasedirectclaim ?membre.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],fr". }
}
LIMIT 100
Try it!

Bbober (talk) 06:47, 8 October 2020 (UTC)Bbober[reply]

[edit]

The item wd:Q14818032 changed to wd:Q189101, I believe. The query does not return any results without this change.

Applied to article. Thank you! Nuretok (talk) 10:47, 2 July 2022 (UTC)[reply]

Error in "Map of places mentioned in travel stories with text in French accessible online"

[edit]

The item "book" (wd:Q571) in the second triple does not yield any results for this query. It should probably be either "written work" (wd:Q47461344) or "literary work" (wd:Q7725634) or a union of both of them.

Periods of Japanese history and what they were named after

[edit]

The query returns no data. --FabC (talk) 18:43, 4 December 2020 (UTC)[reply]

I think the values for instance of (P31) have been changed from era (Q6428674) used in the query to historical period (Q11514315). There are some results if the same change is done in the query but I don't know if all relevant results are found. --Dipsacus fullonum (talk) 00:50, 5 December 2020 (UTC)[reply]
Thanks Dipsacus fullonum, it makes sense. Indeed at least some japanese periods (Kofun period (Q459939), Asuka period (Q210688)) had the value of instance of (P31) changed as you mention. I update the query, cheers --FabC (talk) 09:57, 5 December 2020 (UTC)[reply]

Existing countries by a given date

[edit]

Hello, what about updating https://www.wikidata.org/wiki/Wikidata:SPARQL_query_service/queries/examples#List_of_countries_in_1754 with that one https://w.wiki/q6u ? I'm open to suggestions or objections... Bouzinac💬✒️💛 21:03, 10 December 2020 (UTC)[reply]

examples with the {{SPARQL2}} template have rownums in query

[edit]

Examples like "Total population in the Øresund Region" that use the {{SPARQL2}} template have row-numbers that get read as being part of the query. The template itself hasn't changed recently so some underlying template must be the problem here? --1Veertje (talk) 14:24, 27 December 2020 (UTC)[reply]

there's a phabricator ticket out on this 1Veertje (talk) 22:58, 27 December 2020 (UTC)[reply]

Prolific fathers timing out

[edit]

Hello, the https://www.wikidata.org/wiki/Wikidata:SPARQL_query_service/queries/examples#Most_prolific_fathers do time out. --Bouzinac💬✒️💛 20:53, 18 January 2021 (UTC)[reply]

@Bouzinac: The query was very faulty and I have replaced it. The faults were:
  • Wrong logic: It grouped by ?fatherLabel only so if more than one father had the same name, they would be in the same group.
  • Invalid: It used invalid SPARQL code by reusing variable names after AS. It was only by lock (or unlock?) that it didn't give an error for invalid code.
  • Inefficient: It was very inefficient by getting labels and images before grouping, ordering and limiting.
--Dipsacus fullonum (talk) 22:17, 18 January 2021 (UTC)[reply]
[edit]

Numbers of sitelinks for items with Art UK artist ID (P1367) for each language This query:

SELECT ?lang (COUNT(DISTINCT ?article) AS ?count) WHERE {
  ?article schema:about/wdt:P1367 ?yp_id .  # find articles about things with a BBC 'Your paintings' artist identifier
  FILTER (strafter(strbefore(str(?article),".org"), ".") = "wikipedia") .
  ?article schema:inLanguage ?lang .
} GROUP BY ?lang
ORDER BY DESC (?count)
Try it!

rather than the old:

SELECT ?lang (COUNT(DISTINCT ?article) AS ?count) WHERE {
  ?article schema:about/wdt:P1367 ?yp_id .  # find articles about things with a BBC 'Your paintings' artist identifier
  FILTER (SUBSTR(str(?article), 11, 15) = ".wikipedia.org/") .
  ?article schema:inLanguage ?lang .
} GROUP BY ?lang
ORDER BY DESC (?count)
Try it!

doesn't skip over Wikipedia versions like Simple English, and those with more than 2 letters, and is thus more accurate. --1Veertje (talk) 15:09, 23 January 2021 (UTC)[reply]

Right. Another (and usually faster) way to find only Wikipedia sitelinks is to use wikibase:wikiGroup "wikipedia":
SELECT ?lang (COUNT(DISTINCT ?article) AS ?count) WHERE {
  hint:Query hint:optimizer "None".
  ?item wdt:P1367 ?yp_id .  # find articles about things with a BBC 'Your paintings' artist identifier
  ?article schema:about ?item .
  ?article schema:isPartOf / wikibase:wikiGroup "wikipedia" .  hint:Prior hint:gearing "forward".
  ?article schema:inLanguage ?lang .
} GROUP BY ?lang
ORDER BY DESC (?count)
Try it!
--Dipsacus fullonum (talk) 16:45, 23 January 2021 (UTC)[reply]
what does the "hint:Prior hint:gearing "forward" bit do? 1Veertje (talk) 08:26, 24 January 2021 (UTC)[reply]
@1Veertje: The hint generally makes sure that a property chain is searched starting from the left to the right side (called "forward"). Here it checks that each previously found value for ?article is linked to a Wikipedia. The alternative (called "reverse" in a hint) is to start cheching the property chain from the right, i.e. here find solutions to [] wikibase:wikiGroup "wikipedia" first and then find all possible values of ?article that match the property chain and before selecting the intersection with the previously found values. When selecting the default the engine will usually start from a constant value like the text literal "wikipedia". It is obvious to humans that the number of all Wikipedia sitelinks is much greater than the number of all sitelinks in items with P1367 so that the "reverse" direction is a bad choice here, but the engine cannot see that. --Dipsacus fullonum (talk) 19:38, 24 January 2021 (UTC)[reply]
Thank you for the explenation. Can someone with the ability to do so update the example to what you wrote? --1Veertje (talk) 11:55, 29 January 2021 (UTC)[reply]
✓ Done --Dipsacus fullonum (talk) 02:05, 30 January 2021 (UTC)[reply]

Why not the "AUTO_LANGUAGE"?

[edit]

Any reason to prevent users from getting the familiar labels for most examples? Unless the example is for the user to obtain the original names, a machine-readable list or a collection that probably has no English labels, I think it is better to use the automatic language like wikibase:language "[AUTO_LANGUAGE],en" (I guess it uses the current interface language) for most examples rather than a hard-coded languages list. Looking forward to the answer. --YFdyh000 (talk) 22:29, 8 February 2021 (UTC)[reply]

Do you mean [AUTO_LANGUAGE] will have the default value is "en"?  A l p h a m a  04:01, 2 September 2021 (UTC)[reply]
As per Wikidata:SPARQL_query_service/Wikidata_Query_Help/Result_Views#Auto_language, AUTO_LANGUAGE will be the users language. I agree that it would be helpful to have the example use AUTO_LANGUAGE and only use hard-coded languages when necessary for the example. Nuretok (talk) 10:51, 2 July 2022 (UTC)[reply]

More translatable for comments

[edit]

I think more comments (//) should be marked as translatable (<translate>), thereby providing less unfamiliar English to users. It is better if it can be marked as optional translations. --YFdyh000 (talk) 22:38, 8 February 2021 (UTC)[reply]

Not sure but Wikidata is not Meta so multilingual does not really need here.  A l p h a m a  03:46, 2 September 2021 (UTC)[reply]
Inside a wiki template, to help document, with this {{LangSwitch}}, might be worth trying to write //i'm english--Bouzinac💬✒️💛 07:20, 2 September 2021 (UTC)[reply]
I think it is helpful but to do so. We then must split the examples in sub-pages. When using this template, it may make the page more bulky.  A l p h a m a  15:57, 2 September 2021 (UTC)[reply]
I don't get your point? See for instance : https://www.wikidata.org/wiki/Wikidata:SPARQL_query_service/queries/examples#Cats Bouzinac💬✒️💛 17:40, 2 September 2021 (UTC)[reply]

N°7.23 Query does not work

[edit]

https://www.wikidata.org/wiki/Wikidata:SPARQL_query_service/queries/examples#ATMs_around_Munich_belonging_to_the_Bankcard-Servicenetz_interbank_network_(federated_query)

Zika label query

[edit]

Wikidata:SPARQL_query_service/queries/examples#Scholarly_articles_with_"Zika"_in_the_item_label is timeouting.--Jklamo (talk) 17:52, 2 September 2021 (UTC)[reply]

Descriptive tvar names

[edit]

Does anybody object to making tvar names more descriptive? Currently, most of them are just $1, $2, etc.

For translating a text like this, it would be more useful to give them readable self-documenting names. Amir E. Aharoni {{🌎🌍🌏}} talk 07:51, 22 December 2021 (UTC)[reply]

... So I did this, but @Ameisenigel reverted it, saying " please do not rename tvars".
Why? Is there a policy or a technical document that recommends against this?
Changing them in existing translations is not a big deal, and for future translators it is more convenient to see descriptive names and not numbers. Amir E. Aharoni {{🌎🌍🌏}} talk 21:34, 31 December 2021 (UTC)[reply]
Well, you say Changing them in existing translations is not a big deal, but who will do this? If someone changed the name of the tvars, they would need to update all outdated translations and that usually just does not happen. If you would update the outdated translations, I am not against renaming tvars. I am just against producing extra work for translators. --Ameisenigel (talk) 07:39, 1 January 2022 (UTC)[reply]

Finding Category Translations

[edit]

I want to find the list of the corresponding English Wikipedia categories of a Turkish category. Is there a similar example? Any help is appreciated.--Alperen (talk) 11:00, 25 December 2021 (UTC)[reply]

StackOverflowError for "Largest cities per country"

[edit]

there is a error StackOverflowError when query "Largest cities per country", anyone can fix it? --Bangbang.S 13:07, 10 March 2022 (UTC)[reply]

Fixed. Infrastruktur (talk) 22:12, 2 July 2022 (UTC)[reply]

Adding explanations in natural language

[edit]

I think that examples are hard to understand without an explanation in natural language. I've tried to add explanation in the first three examples. I still don't know how to add translation markup. Feel free to add it and to improve my explanations. PAC2 (talk) 06:18, 3 July 2022 (UTC)[reply]

example query timeout seems dependent on time of day

[edit]

So an example i've transferred here was taken down, because of a timeout of the query. So after some testing i gotten long query times or the timeout but also sometimes the needed time for the search is under 100ms.

I could observe the same behaviour of a very wide difference in query times with other example queries(eg "American universities founded before the states they reside in were created"). Got for this example query times under 100ms but also timeouts and long query times.


So please dont just remove a new query example without extended testing.

Also @Tagishimon can you revert your removement of the example query "Search for lighthouse ranges..." or are here any disagreements here? R Focke (talk) 07:30, 27 April 2023 (UTC)[reply]

I'd prefer that we do not add queries which time out, to the example list. You say "So please dont just remove a new query example without extended testing." I say "So please dont just add a new query example without adequate optimization." The most interesting thing about your query is not the maths, nor the question of why you would take this approach rather than use normalised value nodes, but why it takes so damn long to do so little. --Tagishsimon (talk) 13:35, 27 April 2023 (UTC)[reply]
Im not sure why under 100ms is "so damn long". Im not sure why sometimes they take so much longer. Maybe a prioritization thing?
And i cant optimize things, that were deleted. And, when i implemented it, it was optimized(<100ms), so i dont get what your problem is:P . But that aside, leaving out the "SORT by" part may make it a little more succesful in getting a short queue, it still gets sometimes a timeout error(but i think less often). But unless there is an explanation, why there is such a difference in needed time for the same query, i wouldnt view that as such a problem.
To the normalised value nodes: I work with the things i have been given. And the first thing i found out, was that normalization approach. And with the search "normali[zs]ed value node" no explanation is found, so please dont be so condescending. R Focke (talk) 14:42, 27 April 2023 (UTC)[reply]

Problem in ImageGrid with 2 variables in Presidents and spouses example

[edit]

When the results are viewed with ImageGrid, then, instead of displaying a picture of President (?ppicture) + a picture of Spouse (?wpicture), each ?wpicture is displayed twice. / A generic bug in ImageGrid with 2 variables?. MikiWiki-001 (talk) 12:10, 6 March 2024 (UTC)[reply]

Recent (March 2024) problem with Compare versions

[edit]

Comparing versions (recent or not) recently (March 2024) became abnormaly long, and for any 2 versions selected, the results always display modified blank characters between tags, all along the document. And also, when we do (successfully) some translation or change in a paragraph in a translated page, it now displays afterwards a beige warning "This topic cannot be found". - Could it be related to the "March 19, 2024" modification labelled "translation tags" ? MikiWiki-001 (talk) 08:09, 27 March 2024 (UTC)[reply]

As by March 29th 06:20 UTC, this problem does not show up [only if] we compare 2 versions that are both later than "March 24th 08:20 Minorax". MikiWiki-001 (talk) 06:24, 29 March 2024 (UTC)[reply]
In fact, it seems that each time a new translation unit is added inside a page, then, apparently all the units following that unit are (resequenced?) and listed in the compare page, with a kind of invisible character replaced by itself in each unit. So, I guess that it is normal, and possibly not a problem, although somewhat confusing. MikiWiki-001 (talk) 11:11, 6 July 2024 (UTC)[reply]

Rename to WDQS_examples

[edit]

The examples here are very much specific to WDQS.

Now that we have a better, faster and maintained engine, QLever, I suggest we rename this page to avoid confused users.

After the rename I suggest we create a new page with examples that work on QLever. For queries that time out in WDQS we can refer to a working query on QLever and link to it from the query that times out on this page. WDYT? So9q (talk) 08:16, 24 April 2024 (UTC)[reply]

Wikidata:SPARQL query service is already about Wikidata's query service. Renaming the pages would be a lot of effort (and probably also disruptive) for very little benefit. The pages have subpages and are translatable, and this page is used by the query service itself to load examples, so there are lots of things that would have to move and/or be updated. I don't think adding an acronym to the page name will make it clearer for the majority of people, who are probably not sure what the letters stand for and are probably unaware that there are third-party endpoints running different software. - Nikki (talk) 09:05, 25 April 2024 (UTC)[reply]

Can we have a "shallow end" in this pool

[edit]

(moved from /en-gb)

I have been writing SQL for thirty years and working with database generally even longer but find SPARQL confusing, all the example seem very clever but seem to lack a simple demonstration of where to begin.

For example, though I could use the visual tool to show me all the records with a certain property, showing those properties is counter intuitive and so an example would be good.

My concern is that if I as someone used the databases is finding it confusing there must be many more who are less experienced and are turned-off too Back ache (talk) 02:25, 7 February 2024 (UTC)[reply]

Does the query helper (the "i" icon on the left) or the query builder (button in the bar across the top) help at all?
I would recommend looking at some of the other documentation, e.g. https://wdqs-tutorial.toolforge.org/ or Wikidata:SPARQL_tutorial, if you want to understand the syntax better - the examples are examples of queries you can do, they're not really structured as a tutorial.
I've also seen a lot of people recommend User:Ijon's videos, I think they might be referring to File:Querying_Wikidata_with_SPARQL_for_Absolute_Beginners.webm but if there are others, maybe someone can link them. - Nikki (talk) 09:37, 25 April 2024 (UTC)[reply]
Yes, that's one, and this is a more recent version, with possibly better sound. Asaf Bartov (talk) 22:06, 2 May 2024 (UTC)[reply]

Effect on putting a title inside a query

[edit]

I wish to point out that when a query has a title (#title) in the (engliah) source page, then this title appears untranslated (and untranslatable) in the executable line of the query in each locale translation page, instead of the automatic locale equivalent of "Try it". This seems to contradict the intent of point #13 above (Translate the name of the queries). MikiWiki-001 (talk) 10:42, 27 April 2024 (UTC)[reply]

As demonstrated by the modification made by User:Wladek92 (June 15th 2024 20:48) in the source page, putting translate tags inside the #title line of the query seems to resolve the problem: this creates a new translation unit, and the line may then be translated, which results in the locale execute line (the equivalent of Try it) to be modified in accordance as well. (Apparently, when there is no #title, then for the locale equivalent of Try it to appear in the locale language page, the user must be logged in in that language.) MikiWiki-001 (talk) 05:19, 18 June 2024 (UTC)[reply]
Other point of interest initiating my proposal -> https://www.wikidata.org/wiki/Template_talk:SPARQL#problem_with_WDQS_#title:_and_TryIt --Christian 🇫🇷 FR (talk) 05:48, 18 June 2024 (UTC)[reply]

Header markup generation change fallout

[edit]

Examples aren't loading here or on Commons, likely due to a recent change in header markup generation. I filed issue T366871 to track this. GreenReaper (talk) 07:45, 7 June 2024 (UTC)[reply]

Examples are now back - hopefully, the way they were to start with. GreenReaper (talk) 14:37, 14 June 2024 (UTC)[reply]

UN member states has UK twice

[edit]

The query to find the UN member states currently has 194 instead of the expected 193 entries. United Kingdom is listed twice as Q145 and Q124653007 (realm of UK). Maybe someone can solve this? Thanks.--178.201.237.97 14:27, 11 July 2024 (UTC)[reply]