Negation
Find entities that lack certain properties or relationships. SPARQL provides FILTER NOT EXISTS and MINUS to exclude results matching specific patterns.
Understanding Negation
Negation in SPARQL lets you find things that DON'T have a property or relationship. FILTER NOT EXISTS checks if a pattern doesn't match, while MINUS subtracts matching solutions. Both achieve similar results but work differently with variable bindings.
FILTER NOT EXISTS
SELECT ?person ?personLabel ?birth
WHERE {
?person wdt:P31 wd:Q5 ;
wdt:P106 wd:Q82955 ;
wdt:P569 ?birth .
FILTER NOT EXISTS { ?person wdt:P570 ?death . }
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
LIMIT 20
FILTER NOT EXISTS checks if the inner pattern does NOT match for each result. Politicians without a death date (P570) are returned. This is the most common way to find entities missing a property.
SELECT ?country ?countryLabel
WHERE {
?country wdt:P31 wd:Q6256 .
FILTER NOT EXISTS { ?country wdt:P35 ?monarch . }
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
ORDER BY ?countryLabel
This finds countries that don't have a head of state who is a monarch. The inner pattern checks for the "head of state" property (P35), and countries without it are returned.
Using MINUS
SELECT ?person ?personLabel
WHERE {
?person wdt:P31 wd:Q5 ;
wdt:P106 wd:Q901 ;
wdt:P27 wd:Q30 .
MINUS {
?person wdt:P166 ?award .
?award wdt:P31 wd:Q7191 .
}
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
LIMIT 20
MINUS subtracts solutions that match the inner pattern. This finds American scientists, then removes those who have received a Nobel Prize (award of instance Q7191). The result is scientists who haven't won a Nobel.
Negating Specific Values
SELECT ?city ?cityLabel ?countryLabel
WHERE {
?city wdt:P31 wd:Q515 ;
wdt:P1082 ?pop ;
wdt:P17 ?country .
FILTER(?pop > 5000000)
FILTER NOT EXISTS { ?city wdt:P17 wd:Q30 . }
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
ORDER BY DESC(?pop)
This combines a population filter with negation to find large cities not in the USA. The NOT EXISTS checks specifically for country = Q30 (USA), excluding only American cities while keeping cities from other countries.
Key Entities Used in Examples
| Entity | ID | Description |
|---|---|---|
| human | wd:Q5 | Any human being |
| politician | wd:Q82955 | Person in politics |
| scientist | wd:Q901 | Person who conducts research |
| country | wd:Q6256 | Sovereign state |
| city | wd:Q515 | Large human settlement |
| United States | wd:Q30 | Country in North America |
| Nobel Prize | wd:Q7191 | Annual international awards |
| date of death | wdt:P570 | Date when person died |
| head of state | wdt:P35 | Official head of country |
| award received | wdt:P166 | Award or honor received |