Wikibase/Indexing/SPARQL Query Examples

Syntax according to RDF Dump format. See also https://phabricator.wikimedia.org/T86786

Standard Prefixes
These should be used every time before the query: PREFIX wd:  PREFIX wdt:  PREFIX wikibase:  PREFIX v:  PREFIX q: 

US presidents and wives
SELECT ?p ?w ?l ?wl WHERE { wd:Q30 wdt:P6 ?p. ?p wdt:P26 ?w. OPTIONAL { ?p schema:label ?l filter (lang(?l) = "en"). ?w schema:label ?wl filter (lang(?wl) = "en"). } }

Presidents & causes of death
SELECT ?h ?cause ?hl ?causel WHERE { ?h wdt:P39 wd:Q11696. ?h wdt:P509 ?cause. OPTIONAL { ?h schema:label ?hl filter (lang(?hl) = "en"). ?cause schema:label ?causel filter (lang(?causel) = "en"). } }

People born before year 1880 with no death date
SELECT ?h ?date WHERE { ?h wdt:P31 entity:Q5. ?h wdt:P569 ?date. FILTER NOT EXISTS {?h wdt:P570 ?d } FILTER (?date < "1880-01-01T00:00:00Z"^^xsd:dateTime) } LIMIT 100

Largest cities with female mayor
SELECT DISTINCT ?city ?citylabel ?mayorlabel WHERE { ?city wdt:P31/wdt:P279* wd:Q515. # find instances of subclasses of city ?city wd:P6 ?statement. # with a P6 (head of goverment) statement ?statement v:P6 ?mayor. # ... that has the value ?mayor ?mayor wdt:P21 wd:Q6581072. # ... where the ?mayor has P21 (sex or gender) female FILTER NOT EXISTS { ?statement q:P582 ?x } # ... but the statement has no P582 (end date) qualifier # Now select the population value of the ?city # (the number is reached through a chain of three properties) ?city wdt:P1082 ?population. # Optionally, find English labels for city and mayor: OPTIONAL { ?city rdfs:label ?citylabel. FILTER ( LANG(?citylabel) = "en" ) } OPTIONAL { ?mayor rdfs:label ?mayorlabel. FILTER ( LANG(?mayorlabel) = "en" ) } } ORDER BY DESC(?population) LIMIT 10

List of countries ordered by the number of their cities with female mayor
SELECT ?country ?label (count(*) as ?count) WHERE { ?city wdt:P31/wdt:P279* wd:Q515. # find instances of subclasses of city ?city wd:P6 ?statement. # with a P6 (head of goverment) statement ?statement v:P6 ?mayor. # ... that has the value ?mayor ?mayor wdt:P21 wd:Q6581072. # ... where the ?mayor has P21 (sex or gender) female FILTER NOT EXISTS { ?statement q:P582 ?x } # ... but the statement has no P582 (end date) qualifier ?city wdt:P17 ?country  # Also find the country of the city # If available, get the en label of the country: OPTIONAL { ?country rdfs:label ?label. FILTER ( LANG(?label) = "en" ) } } GROUP BY ?country ?label ORDER BY DESC(?count) LIMIT 100