Cheatsheets:SPARQL: Difference between revisions

From Wikibase
Jump to navigation Jump to search
Fix: running-example table delimiters; keep inline syntaxhighlight mid-line (line-start tags render as block pre) (via update-page on MediaWiki MCP Server)
Standardize: add copy button to block code snippets
 
(26 intermediate revisions by 2 users not shown)
Line 1: Line 1:
{{Cheatsheet}}
{{Cheatsheet}}


SPARQL 1.1 quick syntax reference — for people who already know what SPARQL is
If you are new to SPARQL, see [[FOSS:SPARQL|SPARQL101]].
and need reminders on syntax. All examples run as-is against the public
Wikidata endpoint <syntaxhighlight lang="text" inline>https://query.wikidata.org/sparql</syntaxhighlight>.
For a proper tutorial, take the
[https://www.wikidata.org/wiki/Wikidata:SPARQL_tutorial Wikidata SPARQL tutorial].
For querying a different Wikibase instance (endpoint, prefixes, label service),
see [[Help:Contributing/query]].


== Running example ==
<blockquote>
Examples featured in this cheatsheet run as-is against the public Wikidata endpoint <syntaxhighlight lang="text" inline>https://query.wikidata.org/sparql</syntaxhighlight>. Querying another Wikibase instance is similar, but small query adjustments may be necessary depending on how each instance is set up. See the documentation for your target instance for more info.
</blockquote>


How many dogs and cats are in Wikidata?
== Basic example ==


<syntaxhighlight lang="sparql">
Natural language question:
# wd: = entity (Q…), wdt: = property value (P…), SERVICE = label lookup
 
<syntaxhighlight lang="text" copy>
How many dogs and cats are featured in Wikidata?
</syntaxhighlight>
 
SPARQL query:
 
<syntaxhighlight lang="sparql" copy>
SELECT ?animal ?animalLabel (COUNT(?item) AS ?count) WHERE {
SELECT ?animal ?animalLabel (COUNT(?item) AS ?count) WHERE {
   VALUES ?animal { wd:Q144 wd:Q146 }        # dog, cat
   VALUES ?animal { wd:Q144 wd:Q146 }        # dog, cat
Line 22: Line 25:
GROUP BY ?animal ?animalLabel
GROUP BY ?animal ?animalLabel
</syntaxhighlight>
</syntaxhighlight>
Result as of 2026-08-19:
<syntaxhighlight lang="text" copy>
dog  553
cat  239
</syntaxhighlight>
== Building a query ==
A query is a list of '''triple patterns'''(
<syntaxhighlight lang="sparql" inline>subject predicate object</syntaxhighlight>).
Knowing one or two elements, you can query the rest:


{| class="wikitable"
{| class="wikitable"
! Animal !! Count
! Question !! Known parts !! Pattern
|-
| "What is the population of France?" || subject France (wd:Q142) + predicate population (wdt:P1082) || <syntaxhighlight lang="sparql" inline>wd:Q142 wdt:P1082 ?population .</syntaxhighlight>
|-
|-
| dog || 553
| "Which things are dogs?" || predicate instance-of (wdt:P31) + object dog (wd:Q144) || <syntaxhighlight lang="sparql" inline>?x wdt:P31 wd:Q144 .</syntaxhighlight>
|-
|-
| cat || 239
| "What is known about Einstein?" || subject Einstein (wd:Q937) || <syntaxhighlight lang="sparql" inline>wd:Q937 ?predicate ?value .</syntaxhighlight>
|}
|}


Line 36: Line 54:
! Form !! Returns !! Use when
! Form !! Returns !! Use when
|-
|-
| SELECT || table of variable bindings || you want rows of data (the rest of this sheet)
| SELECT || table of variable bindings || you want rows of data
|-
|-
| ASK || true/false || you only need to know whether something exists
| ASK || true/false || you only need to know whether something exists
Line 45: Line 63:
|}
|}


<syntaxhighlight lang="sparql">
'''SELECT''' — what is the population of France?
# Is there at least one dog in Wikidata?
 
ASK WHERE { ?x wdt:P31 wd:Q144 . }         # → true
<syntaxhighlight lang="sparql" copy>
SELECT ?population WHERE {
  wd:Q142 wdt:P1082 ?population .
}
</syntaxhighlight>
 
Result:
<syntaxhighlight lang="text" copy>
68605616
</syntaxhighlight>


# Every dog as an RDF graph (first two)
'''ASK''' — is there at least one dog in Wikidata?
 
<syntaxhighlight lang="sparql" copy>
ASK WHERE { ?x wdt:P31 wd:Q144 . }
</syntaxhighlight>
 
Result:
<syntaxhighlight lang="text" copy>
true
</syntaxhighlight>
 
'''CONSTRUCT''' — every dog as RDF (first two). Each result row becomes a
triple <syntaxhighlight lang="sparql" inline>?x wdt:P31 wd:Q144</syntaxhighlight>:
 
<syntaxhighlight lang="sparql" copy>
CONSTRUCT { ?x wdt:P31 wd:Q144 . }
CONSTRUCT { ?x wdt:P31 wd:Q144 . }
WHERE { ?x wdt:P31 wd:Q144 . } LIMIT 2
WHERE { ?x wdt:P31 wd:Q144 . } LIMIT 2
</syntaxhighlight>
</syntaxhighlight>


== Triple patterns & literals ==
Result (visualised, N-Triples style):
<syntaxhighlight lang="text" copy>
Q186486  wdt:P31  wd:Q144
Q280571  wdt:P31  wd:Q144
</syntaxhighlight>


A triple pattern is <syntaxhighlight lang="sparql" inline>subject predicate object .</syntaxhighlight> —
'''DESCRIBE''' — everything known about Einstein (all triples with wd:Q937 as
each part may be a variable, an IRI, or a literal.
subject or object):


<syntaxhighlight lang="sparql">
<syntaxhighlight lang="sparql" copy>
# What is the population of France? (→ 68,605,616)
DESCRIBE wd:Q937
SELECT ?population WHERE {
</syntaxhighlight>
  wd:Q142 wdt:P1082 ?population .
}


# Literals can carry datatypes or language tags:
Result (visualised, N-Triples style, first few of thousands):
#  "42"^^xsd:integer      "2026-08-19"^^xsd:date
<syntaxhighlight lang="text" copy>
#   "dog"@en               "chien"@fr
Q937  rdfs:label   "Albert Einstein"@en
# A blank node means "some unnamed thing":
Q937  wdt:P569    1879-03-14
#  wd:Q144 wdt:depicted-by [] .    # dog depicted by something
Q937  wdt:P570    1955-04-18
Q937  wdt:P21      wd:Q6581097  # male
</syntaxhighlight>
</syntaxhighlight>


== Solution modifiers ==
== Solution modifiers ==
'''DISTINCT''' — drop duplicate rows. Einstein and Obama are both male, so the
gender repeats:


{| class="wikitable"
{| class="wikitable"
! Clause !! What it does
! Without !! With DISTINCT
|-
|-
| DISTINCT || drop duplicate rows
|
<syntaxhighlight lang="sparql" copy>
SELECT ?genderLabel WHERE {
  VALUES ?person { wd:Q937 wd:Q76 }
  ?person wdt:P21 ?gender .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
</syntaxhighlight>
 
Result:
<syntaxhighlight lang="text" copy>
male
male
</syntaxhighlight>
||
<syntaxhighlight lang="sparql" line highlight="1" copy>
SELECT DISTINCT ?genderLabel WHERE {
  VALUES ?person { wd:Q937 wd:Q76 }
  ?person wdt:P21 ?gender .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
</syntaxhighlight>
 
Result:
<syntaxhighlight lang="text" copy>
male
</syntaxhighlight>
|}
 
'''ORDER BY + LIMIT''' — the 3 most populous countries, sorted descending:
 
{| class="wikitable"
! Without (arbitrary order) !! With ORDER BY DESC + LIMIT
|-
|-
| ORDER BY || sort (ASC(?) / DESC(?))
|
<syntaxhighlight lang="sparql" copy>
SELECT ?countryLabel ?population WHERE {
  VALUES ?country { wd:Q148 wd:Q30 wd:Q668 }  # China, US, India
  ?country wdt:P1082 ?population .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
</syntaxhighlight>
 
Result:
<syntaxhighlight lang="text" copy>
United States        340110988
China              1404890000
India              1326093247
</syntaxhighlight>
||
<syntaxhighlight lang="sparql" line highlight="6" copy>
SELECT ?countryLabel ?population WHERE {
  VALUES ?country { wd:Q148 wd:Q30 wd:Q668 }
  ?country wdt:P1082 ?population .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
ORDER BY DESC(?population)
</syntaxhighlight>
 
Result:
<syntaxhighlight lang="text" copy>
China              1404890000
India              1326093247
United States        340110988
</syntaxhighlight>
|}
 
'''LIMIT''' — at most n rows:
 
{| class="wikitable"
! Without (all 3) !! With LIMIT 2
|-
|-
| LIMIT n || at most n rows
|
<syntaxhighlight lang="sparql" copy>
SELECT ?countryLabel WHERE {
  VALUES ?country { wd:Q148 wd:Q30 wd:Q668 }
  ?country wdt:P1082 ?population .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
</syntaxhighlight>
 
Result:
<syntaxhighlight lang="text" copy>
United States
China
India
</syntaxhighlight>
||
<syntaxhighlight lang="sparql" line highlight="6" copy>
SELECT ?countryLabel WHERE {
  VALUES ?country { wd:Q148 wd:Q30 wd:Q668 }
  ?country wdt:P1082 ?population .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
LIMIT 2
</syntaxhighlight>
 
Result:
<syntaxhighlight lang="text" copy>
United States
China
</syntaxhighlight>
|}
 
'''OFFSET''' — skip rows (paging). The 2nd most populous country:
 
{| class="wikitable"
! With LIMIT 1 (first) !! With LIMIT 1 OFFSET 1 (second)
|-
|-
| OFFSET n || skip n rows (paging)
|
|-
<syntaxhighlight lang="sparql" copy>
| GROUP BY || group rows for aggregation (see Aggregates)
SELECT ?countryLabel ?population WHERE {
|}
  ?country wdt:P31 wd:Q6256 .
  ?country wdt:P1082 ?population .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
ORDER BY DESC(?population)
LIMIT 1
</syntaxhighlight>


<syntaxhighlight lang="sparql">
Result:
# The 3 most populous countries (ORDER BY + LIMIT)
<syntaxhighlight lang="text" copy>
China  1404890000
</syntaxhighlight>
||
<syntaxhighlight lang="sparql" line highlight="7" copy>
SELECT ?countryLabel ?population WHERE {
SELECT ?countryLabel ?population WHERE {
   ?country wdt:P31 wd:Q6256 .             # instance of: sovereign state
   ?country wdt:P31 wd:Q6256 .
   ?country wdt:P1082 ?population .
   ?country wdt:P1082 ?population .
   SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
   SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
}
ORDER BY DESC(?population)
ORDER BY DESC(?population)
LIMIT 3
LIMIT 1 OFFSET 1
</syntaxhighlight>
 
Result:
<syntaxhighlight lang="text" copy>
India  1326093247
</syntaxhighlight>
|}
 
== VALUES & BIND ==
 
VALUES restricts a variable to a list; BIND computes a new variable.
 
<syntaxhighlight lang="sparql" copy>
SELECT ?personLabel ?birthYear WHERE {
  VALUES ?person { wd:Q937 wd:Q76 }        # Einstein, Obama
  ?person wdt:P569 ?birth .
  BIND(YEAR(?birth) AS ?birthYear)
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
</syntaxhighlight>
</syntaxhighlight>


Result: China 1,404,890,000 · India 1,326,093,247 · United States 340,110,988
Result:
<syntaxhighlight lang="text" copy>
Albert Einstein  1879
Barack Obama    1961
</syntaxhighlight>


== FILTER ==
== FILTER ==
Line 108: Line 292:
| comparison || = < > <= >= !=
| comparison || = < > <= >= !=
|-
|-
| logical || && || !
| logical || <syntaxhighlight lang="sparql" inline>&& || !</syntaxhighlight>
|-
|-
| string || STR() CONTAINS() STRSTARTS() REGEX()
| string || STR() CONTAINS() STRSTARTS() STRENDS() REGEX()
|-
|-
| numeric || ABS() ROUND() FLOOR() CEIL()
| numeric || ABS() ROUND() FLOOR() CEIL()
Line 119: Line 303:
|}
|}


<syntaxhighlight lang="sparql">
'''comparison''' — countries with more than 1 billion people:
# Countries with more than 1 billion people (→ China, India)
 
<syntaxhighlight lang="sparql" copy>
SELECT ?countryLabel ?population WHERE {
SELECT ?countryLabel ?population WHERE {
   ?country wdt:P31 wd:Q6256 .
   ?country wdt:P31 wd:Q6256 .
Line 127: Line 312:
   SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
   SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
}
</syntaxhighlight>


# France's population in millions (FILTER + BIND arithmetic)
Result:
SELECT ?population ?millions WHERE {
<syntaxhighlight lang="text" copy>
China  1404890000
India  1326093247
</syntaxhighlight>
 
'''logical (AND)''' — countries with 300M–500M people:
 
<syntaxhighlight lang="sparql" copy>
SELECT ?countryLabel ?population WHERE {
  ?country wdt:P31 wd:Q6256 .
  ?country wdt:P1082 ?population .
  FILTER(?population > 300000000 && ?population < 500000000)
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
</syntaxhighlight>
 
Result:
<syntaxhighlight lang="text" copy>
United States  340110988
</syntaxhighlight>
 
'''string (STRSTARTS)''' — countries whose English label starts with "S":
 
<syntaxhighlight lang="sparql" copy>
SELECT ?countryLabel WHERE {
  ?country wdt:P31 wd:Q6256 .
  ?country rdfs:label ?countryLabel .
  FILTER(LANG(?countryLabel) = "en" && STRSTARTS(?countryLabel, "S"))
}
LIMIT 3
</syntaxhighlight>
 
Result:
<syntaxhighlight lang="text" copy>
Saint Kitts and Nevis
Somaliland
Saint Vincent and the Grenadines
</syntaxhighlight>
 
'''numeric (ROUND)''' — France's population in millions, rounded:
 
<syntaxhighlight lang="sparql" copy>
SELECT ?millions (ROUND(?millions) AS ?rounded) WHERE {
   wd:Q142 wdt:P1082 ?population .
   wd:Q142 wdt:P1082 ?population .
   BIND(?population / 1000000 AS ?millions)
   BIND(?population / 1000000 AS ?millions)
}                                         # → 68.605616
}
</syntaxhighlight>
 
Result:
<syntaxhighlight lang="text" copy>
68.605616 69
</syntaxhighlight>
 
'''date/time (YEAR)''' — Einstein's birth year:
 
<syntaxhighlight lang="sparql" copy>
SELECT ?personLabel (YEAR(?birth) AS ?birthyear) WHERE {
  wd:Q937 wdt:P569 ?birth .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
</syntaxhighlight>
 
Result:
<syntaxhighlight lang="text" copy>
Albert Einstein  1879
</syntaxhighlight>
 
'''term test (isIRI)''' — the values of <syntaxhighlight lang="sparql" inline>wdt:P31</syntaxhighlight> on a dog
are entities (IRIs), not literals:
 
<syntaxhighlight lang="sparql" copy>
SELECT ?o WHERE {
  wd:Q144 wdt:P31 ?o .
  FILTER(isIRI(?o))
}
</syntaxhighlight>
 
Result:
<syntaxhighlight lang="text" copy>
http://www.wikidata.org/entity/Q55983715
http://www.wikidata.org/entity/Q136772238
</syntaxhighlight>
</syntaxhighlight>


== VALUES & BIND ==
<blockquote>'''Gotcha:''' an unbound variable in a FILTER makes the row fail (unbound ≠ false) — guard with <syntaxhighlight lang="sparql" inline>BOUND()</syntaxhighlight> or restructure with OPTIONAL.
 
The unbound FILTER fails silently. This returns '''no rows''', although
Einstein exists and was born in 1879:
 
<syntaxhighlight lang="sparql" copy>
SELECT ?personLabel WHERE {
  VALUES ?person { wd:Q937 }
  ?person rdfs:label ?personLabel .
  FILTER(LANG(?personLabel) = "en" && ?birthYear = 1879)  # ?birthYear never bound
}
</syntaxhighlight>
 
Result:
<syntaxhighlight lang="text" copy>
(no rows — the FILTER on an unbound variable dropped Einstein)
</syntaxhighlight>


<syntaxhighlight lang="sparql">
Fix: bind the variable first, then filter:
# Restrict ?animal to a fixed list (see the running example)
VALUES ?animal { wd:Q144 wd:Q146 }


# Compute a new variable from existing ones
<syntaxhighlight lang="sparql" copy>
BIND(?population / 1000000 AS ?millions)
SELECT ?personLabel WHERE {
  VALUES ?person { wd:Q937 }
  ?person wdt:P569 ?birth .
  BIND(YEAR(?birth) AS ?birthYear)
  ?person rdfs:label ?personLabel .
  FILTER(LANG(?personLabel) = "en" && ?birthYear = 1879)
}
</syntaxhighlight>
</syntaxhighlight>


== OPTIONAL, UNION, MINUS ==
Result:
<syntaxhighlight lang="text" copy>
Albert Einstein
</syntaxhighlight>
</blockquote>
 
== UNION, OPTIONAL, MINUS ==


{| class="wikitable"
{| class="wikitable"
! Keyword !! Meaning
! Keyword !! Meaning
|-
|-
| OPTIONAL || left join: keep the row, leave the variable unbound when absent
| UNION || pattern A '''OR''' pattern B (the default between patterns is AND, not OR)
|-
|-
| UNION || alternatives (the default between patterns is AND, not OR)
| OPTIONAL || declare a statement optional: do not omit a result entity because it has no value for statement
|-
|-
| MINUS || remove rows that match the pattern
| MINUS || negation: search for things that do '''NOT''' satisfy a given pattern
|}
|}


<syntaxhighlight lang="sparql">
The default between triple patterns is '''AND (join)''': the same variable must
# Einstein (died 1955) vs Obama (alive): OPTIONAL leaves ?deathLabel unbound
satisfy all patterns. The following query returns only dogs that also have an image:
 
<syntaxhighlight lang="sparql" copy>
SELECT ?itemLabel WHERE {
  ?item wdt:P31 wd:Q144 .    # ?item is a dog
  ?item wdt:P18 ?image .      # AND has an image (same ?item!)
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
LIMIT 3
</syntaxhighlight>
 
Result:
<syntaxhighlight lang="text" copy>
Laika
Hachikō
Pickles
</syntaxhighlight>
 
Because the default is AND, when you would like to find something that is/has either A "or" B, you need to use '''UNION'''
{| class="wikitable"
! Without UNION (AND) !! With UNION
|-
|
<syntaxhighlight lang="sparql" copy>
SELECT ?animalLabel (COUNT(?item) AS ?n) WHERE {
  ?item wdt:P31 wd:Q144 .                    # AND: ?item must be a dog
  ?item wdt:P31 wd:Q146 .                    # AND also a cat — impossible!
  BIND("dog" AS ?animalLabel)
}
GROUP BY ?animalLabel
</syntaxhighlight>
 
Result:
<syntaxhighlight lang="text" copy>
(no rows — nothing is both a dog and a cat)
</syntaxhighlight>
||
<syntaxhighlight lang="sparql" copy>
SELECT ?animalLabel (COUNT(?item) AS ?n) WHERE {
  { ?item wdt:P31 wd:Q144 . BIND("dog" AS ?animalLabel) }
  UNION
  { ?item wdt:P31 wd:Q146 . BIND("cat" AS ?animalLabel) }
}
GROUP BY ?animalLabel
</syntaxhighlight>
 
Result:
<syntaxhighlight lang="text" copy>
dog  553
cat  239
</syntaxhighlight>
|}
 
Use '''OPTIONAL''' when you would like to find out something when data is available, but don't care if the data is missing — Einstein (died 1955) vs Obama (alive); ?deathLabel is unbound
for Obama:
 
<syntaxhighlight lang="sparql" copy>
SELECT ?personLabel ?deathLabel WHERE {
SELECT ?personLabel ?deathLabel WHERE {
   VALUES ?person { wd:Q937 wd:Q76 }        # Einstein, Barack Obama
   VALUES ?person { wd:Q937 wd:Q76 }        # Einstein, Barack Obama
Line 164: Line 509:
   SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
   SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
}
# → Albert Einstein  1955-04-18
</syntaxhighlight>
# → Barack Obama    (no death row)


# Nobel laureates minus the French ones (MINUS)
Result:
<syntaxhighlight lang="text" copy>
Albert Einstein  1955-04-18
Barack Obama    (unbound)
</syntaxhighlight>
 
If you do not declare '''OPTIONAL''', Barack Obama will not appear in the results, as there is logically no date of death on his record.
 
Use '''MINUS''' when you would like to find out about things that are/have NOT something
 
E.g., '''non-French''' Nobel laureates:
 
<syntaxhighlight lang="sparql" copy>
SELECT ?personLabel WHERE {
SELECT ?personLabel WHERE {
   ?person wdt:P166 wd:Q7191 .
   ?person wdt:P166 wd:Q7191 .
Line 174: Line 530:
}
}
LIMIT 3
LIMIT 3
</syntaxhighlight>
Result:
<syntaxhighlight lang="text" copy>
Nobel Prize winner
Adam Bernau
Santiago Carril
</syntaxhighlight>


# Dogs AND cats in one result set (UNION + DISTINCT + GROUP BY)
<blockquote>'''Gotcha:''' <syntaxhighlight lang="sparql" inline>FILTER NOT EXISTS</syntaxhighlight> and <syntaxhighlight lang="sparql" inline>MINUS</syntaxhighlight> usually give the same result, but differ when a variable is unbound — prefer MINUS for set-difference semantics.
SELECT ?animalLabel (COUNT(?item) AS ?n) WHERE {
 
   { ?item wdt:P31 wd:Q144 . BIND("dog" AS ?animalLabel) }
Both express "non-French Nobel laureates"; the results are identical:
   UNION
 
   { ?item wdt:P31 wd:Q146 . BIND("cat" AS ?animalLabel) }
<syntaxhighlight lang="sparql" copy>
# FILTER NOT EXISTS
SELECT ?personLabel WHERE {
   ?person wdt:P166 wd:Q7191 .
  FILTER NOT EXISTS { ?person wdt:P27 wd:Q142 . }
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
LIMIT 3
</syntaxhighlight>
 
<syntaxhighlight lang="sparql" copy>
# MINUS
SELECT ?personLabel WHERE {
   ?person wdt:P166 wd:Q7191 .
   MINUS { ?person wdt:P27 wd:Q142 . }
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
}
GROUP BY ?animalLabel
LIMIT 3
</syntaxhighlight>
 
Result (both):
<syntaxhighlight lang="text" copy>
Nobel Prize winner
Adam Bernau
Santiago Carril
</syntaxhighlight>
</syntaxhighlight>
The difference appears only when a variable inside the negated pattern is
unbound: FILTER NOT EXISTS tests per-row (an unbound variable never matches),
while MINUS subtracts whole patterns regardless of unbound variables.
</blockquote>


== Property paths ==
== Property paths ==
Line 189: Line 580:
! Path !! Meaning
! Path !! Meaning
|-
|-
| wdt:P40/wdt:P40 || two hops (sequence)
| wdt:P279/wdt:P279 || two hops (sequence)
|-
|-
| wdt:P40+ || one or more hops
| wdt:P279+ || one or more hops
|-
|-
| wdt:P40* || zero or more hops
| wdt:P279* || zero or more hops (transitive)
|-
|-
| wdt:P40? || zero or one hop
| wdt:P279? || zero or one hop
|-
|-
| wdt:P40|wdt:P41 || either property
| wdt:P279|wdt:P31 || either property
|-
| ^wdt:P279 || inverse direction
|-
| !wdt:P279 || any property except P279
|}
 
A path chains several properties into one pattern. The dog example uses
'''subclass of''' (wdt:P279). Compare the direct pattern with the transitive
(<syntaxhighlight lang="sparql" inline>*</syntaxhighlight> = zero or more hops):
 
{| class="wikitable"
! Pattern !! What it matches !! Live example !! Returns
|-
|-
| ^wdt:P40 || inverse direction
| <syntaxhighlight lang="sparql" inline>?x wdt:P279 wd:Q144</syntaxhighlight> || classes that are a '''direct''' kind of dog (one hop) || <syntaxhighlight lang="sparql" inline>?x wdt:P279 wd:Q144</syntaxhighlight> || Rottweiler, Swedish Vallhund — 314
|-
|-
| !wdt:P40 || any property except P40
| <syntaxhighlight lang="sparql" inline>?x wdt:P279* wd:Q144</syntaxhighlight> || classes that are dog or any kind-of-kind-of-dog (any number of hops) || <syntaxhighlight lang="sparql" inline>?x wdt:P279* wd:Q144</syntaxhighlight> || adds sub-breeds like Norman Hound → scent hound → dog — 511
|}
|}


<syntaxhighlight lang="sparql">
The <syntaxhighlight lang="sparql" inline>*</syntaxhighlight> finds things several hops away that a
# Named dogs, including breeds and other subclasses of dog
single triple cannot:
# (wdt:P31/wdt:P279* = "instance of something that is a dog or a subclass of dog")
 
<syntaxhighlight lang="sparql" copy>
SELECT ?thing ?thingLabel WHERE {
SELECT ?thing ?thingLabel WHERE {
   ?thing wdt:P31/wdt:P279* wd:Q144 .
   ?thing wdt:P279* wd:Q144 .
   SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
   SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
}
Line 214: Line 618:
</syntaxhighlight>
</syntaxhighlight>


Result: Theo · Tich · Tickle Em Jock
Result:
<syntaxhighlight lang="text" copy>
Lapponian Herder
autism assistance dog
diabetic alert dog
</syntaxhighlight>
 
(These are sub-subclasses: Lapponian Herder → herding dog → dog.)
 
<blockquote>'''Gotcha:''' a variable that appears only inside a path is not bound, so it cannot be selected.
 
A two-hop path (<syntaxhighlight lang="sparql" inline>wdt:P279/wdt:P279</syntaxhighlight>) finds dogs two levels down (bloodhound, beagle) — but the intermediate hop is anonymous, so there is nothing to select for it:
 
<syntaxhighlight lang="sparql" copy>
# Path form: intermediate hop is anonymous — ?mid is not available
SELECT ?xLabel WHERE {
  ?x wdt:P279/wdt:P279 wd:Q144 .
  ?x rdfs:label ?xLabel . FILTER(LANG(?xLabel) = "en")
}
LIMIT 3
</syntaxhighlight>
 
Result:
<syntaxhighlight lang="text" copy>
bloodhound
beagle
Chesapeake Bay Retriever
</syntaxhighlight>
 
To select the intermediate value, write two explicit triples with a variable:
 
<syntaxhighlight lang="sparql" copy>
# Explicit form: ?mid is selectable
SELECT ?xLabel ?midLabel WHERE {
  ?x wdt:P279 ?mid .
  ?mid wdt:P279 wd:Q144 .
  ?x rdfs:label ?xLabel . FILTER(LANG(?xLabel) = "en")
  ?mid rdfs:label ?midLabel . FILTER(LANG(?midLabel) = "en")
}
LIMIT 3
</syntaxhighlight>
 
Result:
<syntaxhighlight lang="text" copy>
shepherd dog        pastoral dog
livestock guardian dog  pastoral dog
Canadian Eskimo Dog      inuit sledge dog
</syntaxhighlight>
</blockquote>


== Aggregates ==
== Aggregates ==


COUNT, SUM, AVG, MIN, MAX, SAMPLE (pick one arbitrary value), GROUP_CONCAT.
Aggregates collapse many rows into one per group. All examples use the same
three countries (China, US, India).
 
'''COUNT''' — how many values (the running example counts instances per
animal; here: values of <syntaxhighlight lang="sparql" inline>wdt:P1082</syntaxhighlight> for the three countries):
 
<syntaxhighlight lang="sparql" copy>
SELECT (COUNT(?population) AS ?n) WHERE {
  VALUES ?country { wd:Q148 wd:Q30 wd:Q668 }
  ?country wdt:P1082 ?population .
}
</syntaxhighlight>
 
Result:
<syntaxhighlight lang="text" copy>
3
</syntaxhighlight>
 
'''SUM''' — combined population of the three:
 
<syntaxhighlight lang="sparql" copy>
SELECT (SUM(?population) AS ?total) WHERE {
  VALUES ?country { wd:Q148 wd:Q30 wd:Q668 }
  ?country wdt:P1082 ?population .
}
</syntaxhighlight>
 
Result:
<syntaxhighlight lang="text" copy>
3071094235
</syntaxhighlight>
 
'''AVG''' — mean population of the three:
 
<syntaxhighlight lang="sparql" copy>
SELECT (AVG(?population) AS ?avg) WHERE {
  VALUES ?country { wd:Q148 wd:Q30 wd:Q668 }
  ?country wdt:P1082 ?population .
}
</syntaxhighlight>
 
Result:
<syntaxhighlight lang="text" copy>
1023698078.33
</syntaxhighlight>
 
'''MIN / MAX''' — smallest and largest of the three:
 
<syntaxhighlight lang="sparql" copy>
SELECT (MIN(?population) AS ?min) (MAX(?population) AS ?max) WHERE {
  VALUES ?country { wd:Q148 wd:Q30 wd:Q668 }
  ?country wdt:P1082 ?population .
}
</syntaxhighlight>
 
Result:
<syntaxhighlight lang="text" copy>
340110988  1404890000
</syntaxhighlight>
 
'''SAMPLE''' — one arbitrary value (useful to squash duplicates):
 
<syntaxhighlight lang="sparql" copy>
SELECT (SAMPLE(?countryLabel) AS ?anyCountry) WHERE {
  VALUES ?country { wd:Q148 wd:Q30 wd:Q668 }
  ?country wdt:P1082 ?population .
  ?country rdfs:label ?countryLabel .
  FILTER(LANG(?countryLabel) = "en")
}
</syntaxhighlight>
 
Result:
<syntaxhighlight lang="text" copy>
United States
</syntaxhighlight>
 
'''GROUP_CONCAT''' — Einstein's awards in one cell:


<syntaxhighlight lang="sparql">
<syntaxhighlight lang="sparql" copy>
# Species with more than 400 direct instances (the running example with HAVING)
SELECT ?personLabel (GROUP_CONCAT(?awardLabel; SEPARATOR=", ") AS ?awards) WHERE {
  VALUES ?person { wd:Q937 }
  ?person wdt:P166 ?award .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
GROUP BY ?personLabel
</syntaxhighlight>
 
Result:
<syntaxhighlight lang="text" copy>
Albert Einstein  Nobel Prize in Physics, …
</syntaxhighlight>
 
'''GROUP BY + HAVING''' — the running example, filtered to groups with more
than 400 instances:
 
<syntaxhighlight lang="sparql" copy>
SELECT ?animalLabel (COUNT(?item) AS ?n) WHERE {
SELECT ?animalLabel (COUNT(?item) AS ?n) WHERE {
   VALUES ?animal { wd:Q144 wd:Q146 }
   VALUES ?animal { wd:Q144 wd:Q146 }
Line 228: Line 772:
}
}
GROUP BY ?animal ?animalLabel
GROUP BY ?animal ?animalLabel
HAVING (COUNT(?item) > 400)               # → only dog: 553
HAVING (COUNT(?item) > 400)
</syntaxhighlight>
 
Result:
<syntaxhighlight lang="text" copy>
dog 553
</syntaxhighlight>
 
<blockquote>'''Gotcha:''' aggregates need GROUP BY for every non-aggregated variable. Forgetting one is a '''query error''', not a wrong result.


# Collect labels into one cell
Missing GROUP BY for <syntaxhighlight lang="sparql" inline>?animalLabel</syntaxhighlight>:
SELECT ?personLabel (GROUP_CONCAT(?awardLabel; SEPARATOR=", ") AS ?awards) WHERE {
 
   VALUES ?person { wd:Q937 }
<syntaxhighlight lang="sparql" copy>
   ?person wdt:P166 ?award .
SELECT ?animalLabel (COUNT(?item) AS ?n) WHERE {
   SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
   VALUES ?animal { wd:Q144 wd:Q146 }
   ?item wdt:P31 ?animal .
   ?animal rdfs:label ?animalLabel .
  FILTER(LANG(?animalLabel) = "en")
}
}
GROUP BY ?personLabel
</syntaxhighlight>
</syntaxhighlight>
Result:
<syntaxhighlight lang="text" copy>
ERROR: Bad aggregate — every non-aggregated variable needs GROUP BY
</syntaxhighlight>
</blockquote>


== Subqueries ==
== Subqueries ==
Line 243: Line 803:
A query inside a query — useful for "the X with the max Y" patterns.
A query inside a query — useful for "the X with the max Y" patterns.


<syntaxhighlight lang="sparql">
'''The most populous country, computed via a subquery:'''
# The most populous country, computed via a subquery (→ China)
 
<syntaxhighlight lang="sparql" copy>
SELECT ?countryLabel ?max WHERE {
SELECT ?countryLabel ?max WHERE {
   {
   {
Line 256: Line 817:
   SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
   SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
}
</syntaxhighlight>
Result:
<syntaxhighlight lang="text" copy>
China  1404890000
</syntaxhighlight>
</syntaxhighlight>


Line 263: Line 829:
queries above:
queries above:


<syntaxhighlight lang="sparql">
<syntaxhighlight lang="sparql" copy>
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
# then reference ?xLabel for every ?x in the query
# then reference ?xLabel for every ?x in the query
</syntaxhighlight>
</syntaxhighlight>


<syntaxhighlight lang="sparql">
<syntaxhighlight lang="sparql" copy>
# Federating to another endpoint (needs the remote's own IRIs, e.g. via owl:sameAs)
# Federating to another endpoint (needs the remote's own IRIs, e.g. via owl:sameAs)
SELECT ?cityLabel WHERE {
SELECT ?cityLabel WHERE {
Line 279: Line 845:
}
}
</syntaxhighlight>
</syntaxhighlight>
== Common tasks ==
* '''Count rows''': <syntaxhighlight lang="sparql" inline>SELECT (COUNT(*) AS ?n) WHERE { … }</syntaxhighlight>
* '''Check existence''': <syntaxhighlight lang="sparql" inline>ASK WHERE { … }</syntaxhighlight>
* '''Deduplicate''': add <syntaxhighlight lang="sparql" inline>DISTINCT</syntaxhighlight>
* '''Reverse a relation''': <syntaxhighlight lang="sparql" inline>?child ^wdt:P40 ?parent</syntaxhighlight>
* '''Page through results''': <syntaxhighlight lang="sparql" inline>LIMIT 100 OFFSET 100</syntaxhighlight>
* '''JSON output''': append <syntaxhighlight lang="text" inline>&format=json</syntaxhighlight> to the endpoint URL
== Gotchas ==
* The default between triple patterns is '''AND (join)''' — use UNION for alternatives.
* An unbound variable in <syntaxhighlight lang="sparql" inline>FILTER</syntaxhighlight> makes the row fail (unbound ≠ false) — guard with <syntaxhighlight lang="sparql" inline>BOUND()</syntaxhighlight> or restructure with OPTIONAL.
* Variables used only inside a property path (e.g. <syntaxhighlight lang="sparql" inline>?s wdt:P40/wdt:P40 ?o</syntaxhighlight>) cannot be selected.
* Blank-node labels (<syntaxhighlight lang="sparql" inline>_:x</syntaxhighlight>) are local to one query — they are not IRIs.
* Aggregates need GROUP BY for every non-aggregated variable; forgetting one mixes unrelated rows.
* <syntaxhighlight lang="sparql" inline>FILTER NOT EXISTS</syntaxhighlight> differs from <syntaxhighlight lang="sparql" inline>MINUS</syntaxhighlight> when variables are unbound — prefer MINUS for set-difference semantics.
* Endpoint prefixes are not universal — <syntaxhighlight lang="sparql" inline>wd:</syntaxhighlight>/<syntaxhighlight lang="sparql" inline>wdt:</syntaxhighlight> are Wikidata's; other instances define their own (see [[Help:Contributing/query]]).


== Further reading ==
== Further reading ==

Latest revision as of 09:45, 23 August 2026

Quick reference for smart people — part of our dev cheatsheets collection.

If you are new to SPARQL, see SPARQL101.

Examples featured in this cheatsheet run as-is against the public Wikidata endpoint https://query.wikidata.org/sparql. Querying another Wikibase instance is similar, but small query adjustments may be necessary depending on how each instance is set up. See the documentation for your target instance for more info.

Basic example

Natural language question:

How many dogs and cats are featured in Wikidata?

SPARQL query:

SELECT ?animal ?animalLabel (COUNT(?item) AS ?count) WHERE {
  VALUES ?animal { wd:Q144 wd:Q146 }        # dog, cat
  ?item wdt:P31 ?animal .                   # ?item is an instance of ?animal
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
GROUP BY ?animal ?animalLabel

Result as of 2026-08-19:

dog  553
cat  239

Building a query

A query is a list of triple patterns( subject predicate object). Knowing one or two elements, you can query the rest:

Question Known parts Pattern
"What is the population of France?" subject France (wd:Q142) + predicate population (wdt:P1082) wd:Q142 wdt:P1082 ?population .
"Which things are dogs?" predicate instance-of (wdt:P31) + object dog (wd:Q144) ?x wdt:P31 wd:Q144 .
"What is known about Einstein?" subject Einstein (wd:Q937) wd:Q937 ?predicate ?value .

Query forms

Form Returns Use when
SELECT table of variable bindings you want rows of data
ASK true/false you only need to know whether something exists
CONSTRUCT an RDF graph (triples) you want the result as RDF, not a table
DESCRIBE a graph describing the resource you want everything known about an entity

SELECT — what is the population of France?

SELECT ?population WHERE {
  wd:Q142 wdt:P1082 ?population .
}

Result:

68605616

ASK — is there at least one dog in Wikidata?

ASK WHERE { ?x wdt:P31 wd:Q144 . }

Result:

true

CONSTRUCT — every dog as RDF (first two). Each result row becomes a triple ?x wdt:P31 wd:Q144:

CONSTRUCT { ?x wdt:P31 wd:Q144 . }
WHERE { ?x wdt:P31 wd:Q144 . } LIMIT 2

Result (visualised, N-Triples style):

Q186486  wdt:P31  wd:Q144
Q280571  wdt:P31  wd:Q144

DESCRIBE — everything known about Einstein (all triples with wd:Q937 as subject or object):

DESCRIBE wd:Q937

Result (visualised, N-Triples style, first few of thousands):

Q937  rdfs:label   "Albert Einstein"@en
Q937  wdt:P569     1879-03-14
Q937  wdt:P570     1955-04-18
Q937  wdt:P21      wd:Q6581097   # male

Solution modifiers

DISTINCT — drop duplicate rows. Einstein and Obama are both male, so the gender repeats:

Without With DISTINCT
SELECT ?genderLabel WHERE {
  VALUES ?person { wd:Q937 wd:Q76 }
  ?person wdt:P21 ?gender .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}

Result:

male
male
SELECT DISTINCT ?genderLabel WHERE {
  VALUES ?person { wd:Q937 wd:Q76 }
  ?person wdt:P21 ?gender .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}

Result:

male

ORDER BY + LIMIT — the 3 most populous countries, sorted descending:

Without (arbitrary order) With ORDER BY DESC + LIMIT
SELECT ?countryLabel ?population WHERE {
  VALUES ?country { wd:Q148 wd:Q30 wd:Q668 }   # China, US, India
  ?country wdt:P1082 ?population .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}

Result:

United States        340110988
China               1404890000
India               1326093247
SELECT ?countryLabel ?population WHERE {
  VALUES ?country { wd:Q148 wd:Q30 wd:Q668 }
  ?country wdt:P1082 ?population .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
ORDER BY DESC(?population)

Result:

China               1404890000
India               1326093247
United States        340110988

LIMIT — at most n rows:

Without (all 3) With LIMIT 2
SELECT ?countryLabel WHERE {
  VALUES ?country { wd:Q148 wd:Q30 wd:Q668 }
  ?country wdt:P1082 ?population .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}

Result:

United States
China
India
SELECT ?countryLabel WHERE {
  VALUES ?country { wd:Q148 wd:Q30 wd:Q668 }
  ?country wdt:P1082 ?population .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
LIMIT 2

Result:

United States
China

OFFSET — skip rows (paging). The 2nd most populous country:

With LIMIT 1 (first) With LIMIT 1 OFFSET 1 (second)
SELECT ?countryLabel ?population WHERE {
  ?country wdt:P31 wd:Q6256 .
  ?country wdt:P1082 ?population .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
ORDER BY DESC(?population)
LIMIT 1

Result:

China  1404890000
SELECT ?countryLabel ?population WHERE {
  ?country wdt:P31 wd:Q6256 .
  ?country wdt:P1082 ?population .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
ORDER BY DESC(?population)
LIMIT 1 OFFSET 1

Result:

India  1326093247

VALUES & BIND

VALUES restricts a variable to a list; BIND computes a new variable.

SELECT ?personLabel ?birthYear WHERE {
  VALUES ?person { wd:Q937 wd:Q76 }        # Einstein, Obama
  ?person wdt:P569 ?birth .
  BIND(YEAR(?birth) AS ?birthYear)
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}

Result:

Albert Einstein  1879
Barack Obama     1961

FILTER

Category Operators / functions
comparison = < > <= >= !=
logical && || !
string STR() CONTAINS() STRSTARTS() STRENDS() REGEX()
numeric ABS() ROUND() FLOOR() CEIL()
date/time YEAR() MONTH() DAY() NOW()
term tests isIRI() isBlank() isLiteral() LANG() DATATYPE()

comparison — countries with more than 1 billion people:

SELECT ?countryLabel ?population WHERE {
  ?country wdt:P31 wd:Q6256 .
  ?country wdt:P1082 ?population .
  FILTER(?population > 1000000000)
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}

Result:

China   1404890000
India   1326093247

logical (AND) — countries with 300M–500M people:

SELECT ?countryLabel ?population WHERE {
  ?country wdt:P31 wd:Q6256 .
  ?country wdt:P1082 ?population .
  FILTER(?population > 300000000 && ?population < 500000000)
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}

Result:

United States  340110988

string (STRSTARTS) — countries whose English label starts with "S":

SELECT ?countryLabel WHERE {
  ?country wdt:P31 wd:Q6256 .
  ?country rdfs:label ?countryLabel .
  FILTER(LANG(?countryLabel) = "en" && STRSTARTS(?countryLabel, "S"))
}
LIMIT 3

Result:

Saint Kitts and Nevis
Somaliland
Saint Vincent and the Grenadines

numeric (ROUND) — France's population in millions, rounded:

SELECT ?millions (ROUND(?millions) AS ?rounded) WHERE {
  wd:Q142 wdt:P1082 ?population .
  BIND(?population / 1000000 AS ?millions)
}

Result:

68.605616  69

date/time (YEAR) — Einstein's birth year:

SELECT ?personLabel (YEAR(?birth) AS ?birthyear) WHERE {
  wd:Q937 wdt:P569 ?birth .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}

Result:

Albert Einstein  1879

term test (isIRI) — the values of wdt:P31 on a dog are entities (IRIs), not literals:

SELECT ?o WHERE {
  wd:Q144 wdt:P31 ?o .
  FILTER(isIRI(?o))
}

Result:

http://www.wikidata.org/entity/Q55983715
http://www.wikidata.org/entity/Q136772238

Gotcha: an unbound variable in a FILTER makes the row fail (unbound ≠ false) — guard with BOUND() or restructure with OPTIONAL.

The unbound FILTER fails silently. This returns no rows, although Einstein exists and was born in 1879:

SELECT ?personLabel WHERE {
  VALUES ?person { wd:Q937 }
  ?person rdfs:label ?personLabel .
  FILTER(LANG(?personLabel) = "en" && ?birthYear = 1879)   # ?birthYear never bound
}

Result:

(no rows — the FILTER on an unbound variable dropped Einstein)

Fix: bind the variable first, then filter:

SELECT ?personLabel WHERE {
  VALUES ?person { wd:Q937 }
  ?person wdt:P569 ?birth .
  BIND(YEAR(?birth) AS ?birthYear)
  ?person rdfs:label ?personLabel .
  FILTER(LANG(?personLabel) = "en" && ?birthYear = 1879)
}

Result:

Albert Einstein

UNION, OPTIONAL, MINUS

Keyword Meaning
UNION pattern A OR pattern B (the default between patterns is AND, not OR)
OPTIONAL declare a statement optional: do not omit a result entity because it has no value for statement
MINUS negation: search for things that do NOT satisfy a given pattern

The default between triple patterns is AND (join): the same variable must satisfy all patterns. The following query returns only dogs that also have an image:

SELECT ?itemLabel WHERE {
  ?item wdt:P31 wd:Q144 .     # ?item is a dog
  ?item wdt:P18 ?image .      # AND has an image (same ?item!)
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
LIMIT 3

Result:

Laika
Hachikō
Pickles

Because the default is AND, when you would like to find something that is/has either A "or" B, you need to use UNION

Without UNION (AND) With UNION
SELECT ?animalLabel (COUNT(?item) AS ?n) WHERE {
  ?item wdt:P31 wd:Q144 .                    # AND: ?item must be a dog
  ?item wdt:P31 wd:Q146 .                    # AND also a cat — impossible!
  BIND("dog" AS ?animalLabel)
}
GROUP BY ?animalLabel

Result:

(no rows — nothing is both a dog and a cat)
SELECT ?animalLabel (COUNT(?item) AS ?n) WHERE {
  { ?item wdt:P31 wd:Q144 . BIND("dog" AS ?animalLabel) }
  UNION
  { ?item wdt:P31 wd:Q146 . BIND("cat" AS ?animalLabel) }
}
GROUP BY ?animalLabel

Result:

dog  553
cat  239

Use OPTIONAL when you would like to find out something when data is available, but don't care if the data is missing — Einstein (died 1955) vs Obama (alive); ?deathLabel is unbound for Obama:

SELECT ?personLabel ?deathLabel WHERE {
  VALUES ?person { wd:Q937 wd:Q76 }         # Einstein, Barack Obama
  OPTIONAL { ?person wdt:P570 ?death . }
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}

Result:

Albert Einstein  1955-04-18
Barack Obama     (unbound)

If you do not declare OPTIONAL, Barack Obama will not appear in the results, as there is logically no date of death on his record.

Use MINUS when you would like to find out about things that are/have NOT something

E.g., non-French Nobel laureates:

SELECT ?personLabel WHERE {
  ?person wdt:P166 wd:Q7191 .
  MINUS { ?person wdt:P27 wd:Q142 . }
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
LIMIT 3

Result:

Nobel Prize winner
Adam Bernau
Santiago Carril

Gotcha: FILTER NOT EXISTS and MINUS usually give the same result, but differ when a variable is unbound — prefer MINUS for set-difference semantics.

Both express "non-French Nobel laureates"; the results are identical:

# FILTER NOT EXISTS
SELECT ?personLabel WHERE {
  ?person wdt:P166 wd:Q7191 .
  FILTER NOT EXISTS { ?person wdt:P27 wd:Q142 . }
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
LIMIT 3
# MINUS
SELECT ?personLabel WHERE {
  ?person wdt:P166 wd:Q7191 .
  MINUS { ?person wdt:P27 wd:Q142 . }
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
LIMIT 3

Result (both):

Nobel Prize winner
Adam Bernau
Santiago Carril

The difference appears only when a variable inside the negated pattern is unbound: FILTER NOT EXISTS tests per-row (an unbound variable never matches), while MINUS subtracts whole patterns regardless of unbound variables.

Property paths

Path Meaning
wdt:P279/wdt:P279 two hops (sequence)
wdt:P279+ one or more hops
wdt:P279* zero or more hops (transitive)
wdt:P279? zero or one hop
wdt:P31 either property
^wdt:P279 inverse direction
!wdt:P279 any property except P279

A path chains several properties into one pattern. The dog example uses subclass of (wdt:P279). Compare the direct pattern with the transitive (* = zero or more hops):

Pattern What it matches Live example Returns
?x wdt:P279 wd:Q144 classes that are a direct kind of dog (one hop) ?x wdt:P279 wd:Q144 Rottweiler, Swedish Vallhund — 314
?x wdt:P279* wd:Q144 classes that are dog or any kind-of-kind-of-dog (any number of hops) ?x wdt:P279* wd:Q144 adds sub-breeds like Norman Hound → scent hound → dog — 511

The * finds things several hops away that a single triple cannot:

SELECT ?thing ?thingLabel WHERE {
  ?thing wdt:P279* wd:Q144 .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
LIMIT 3

Result:

Lapponian Herder
autism assistance dog
diabetic alert dog

(These are sub-subclasses: Lapponian Herder → herding dog → dog.)

Gotcha: a variable that appears only inside a path is not bound, so it cannot be selected.

A two-hop path (wdt:P279/wdt:P279) finds dogs two levels down (bloodhound, beagle) — but the intermediate hop is anonymous, so there is nothing to select for it:

# Path form: intermediate hop is anonymous — ?mid is not available
SELECT ?xLabel WHERE {
  ?x wdt:P279/wdt:P279 wd:Q144 .
  ?x rdfs:label ?xLabel . FILTER(LANG(?xLabel) = "en")
}
LIMIT 3

Result:

bloodhound
beagle
Chesapeake Bay Retriever

To select the intermediate value, write two explicit triples with a variable:

# Explicit form: ?mid is selectable
SELECT ?xLabel ?midLabel WHERE {
  ?x wdt:P279 ?mid .
  ?mid wdt:P279 wd:Q144 .
  ?x rdfs:label ?xLabel . FILTER(LANG(?xLabel) = "en")
  ?mid rdfs:label ?midLabel . FILTER(LANG(?midLabel) = "en")
}
LIMIT 3

Result:

shepherd dog        pastoral dog
livestock guardian dog   pastoral dog
Canadian Eskimo Dog      inuit sledge dog

Aggregates

Aggregates collapse many rows into one per group. All examples use the same three countries (China, US, India).

COUNT — how many values (the running example counts instances per animal; here: values of wdt:P1082 for the three countries):

SELECT (COUNT(?population) AS ?n) WHERE {
  VALUES ?country { wd:Q148 wd:Q30 wd:Q668 }
  ?country wdt:P1082 ?population .
}

Result:

3

SUM — combined population of the three:

SELECT (SUM(?population) AS ?total) WHERE {
  VALUES ?country { wd:Q148 wd:Q30 wd:Q668 }
  ?country wdt:P1082 ?population .
}

Result:

3071094235

AVG — mean population of the three:

SELECT (AVG(?population) AS ?avg) WHERE {
  VALUES ?country { wd:Q148 wd:Q30 wd:Q668 }
  ?country wdt:P1082 ?population .
}

Result:

1023698078.33

MIN / MAX — smallest and largest of the three:

SELECT (MIN(?population) AS ?min) (MAX(?population) AS ?max) WHERE {
  VALUES ?country { wd:Q148 wd:Q30 wd:Q668 }
  ?country wdt:P1082 ?population .
}

Result:

340110988  1404890000

SAMPLE — one arbitrary value (useful to squash duplicates):

SELECT (SAMPLE(?countryLabel) AS ?anyCountry) WHERE {
  VALUES ?country { wd:Q148 wd:Q30 wd:Q668 }
  ?country wdt:P1082 ?population .
  ?country rdfs:label ?countryLabel .
  FILTER(LANG(?countryLabel) = "en")
}

Result:

United States

GROUP_CONCAT — Einstein's awards in one cell:

SELECT ?personLabel (GROUP_CONCAT(?awardLabel; SEPARATOR=", ") AS ?awards) WHERE {
  VALUES ?person { wd:Q937 }
  ?person wdt:P166 ?award .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
GROUP BY ?personLabel

Result:

Albert Einstein  Nobel Prize in Physics, …

GROUP BY + HAVING — the running example, filtered to groups with more than 400 instances:

SELECT ?animalLabel (COUNT(?item) AS ?n) WHERE {
  VALUES ?animal { wd:Q144 wd:Q146 }
  ?item wdt:P31 ?animal .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
GROUP BY ?animal ?animalLabel
HAVING (COUNT(?item) > 400)

Result:

dog  553

Gotcha: aggregates need GROUP BY for every non-aggregated variable. Forgetting one is a query error, not a wrong result.

Missing GROUP BY for ?animalLabel:

SELECT ?animalLabel (COUNT(?item) AS ?n) WHERE {
  VALUES ?animal { wd:Q144 wd:Q146 }
  ?item wdt:P31 ?animal .
  ?animal rdfs:label ?animalLabel .
  FILTER(LANG(?animalLabel) = "en")
}

Result:

ERROR: Bad aggregate — every non-aggregated variable needs GROUP BY

Subqueries

A query inside a query — useful for "the X with the max Y" patterns.

The most populous country, computed via a subquery:

SELECT ?countryLabel ?max WHERE {
  {
    SELECT (MAX(?population) AS ?max) WHERE {
      ?c wdt:P31 wd:Q6256 .
      ?c wdt:P1082 ?population .
    }
  }
  ?country wdt:P31 wd:Q6256 .
  ?country wdt:P1082 ?max .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}

Result:

China  1404890000

SERVICE (labels, federation)

The label service turns entity IDs into human-readable labels — used in most queries above:

SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
# then reference ?xLabel for every ?x in the query
# Federating to another endpoint (needs the remote's own IRIs, e.g. via owl:sameAs)
SELECT ?cityLabel WHERE {
  wd:Q64 wdt:P36 ?city .
  ?city owl:sameAs ?dbpediaCity .
  SERVICE <https://dbpedia.org/sparql> {
    ?dbpediaCity rdfs:label ?cityLabel .
    FILTER(LANG(?cityLabel) = "en")
  }
}

Further reading