FILTER
Restrict query results using conditions. FILTER eliminates solutions that don't satisfy a boolean expression, enabling precise data selection.
Understanding FILTER
FILTER tests each potential result against a boolean condition. Only results where
the condition evaluates to true are included in the output.
| Operator | Meaning | Example |
|---|---|---|
= | Equal | ?x = 100 |
!= | Not equal | ?x != 0 |
<, > | Less/greater than | ?pop > 1000000 |
<=, >= | Less/greater or equal | ?year >= 2000 |
&& | Logical AND | ?a > 0 && ?a < 100 |
|| | Logical OR | ?type = "A" || ?type = "B" |
! | Logical NOT | !BOUND(?x) |
Numeric Comparisons
SELECT ?country ?countryLabel ?population
WHERE {
?country wdt:P31 wd:Q6256 ;
wdt:P1082 ?population .
FILTER(?population > 100000000)
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
ORDER BY DESC(?population)
This query finds countries (Q6256) with populations exceeding 100 million. The FILTER clause tests each country's population value.
SELECT ?mountain ?mountainLabel ?elevation
WHERE {
?mountain wdt:P31 wd:Q8502 ;
wdt:P2044 ?elevation .
FILTER(?elevation >= 8000 && ?elevation < 9000)
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
ORDER BY DESC(?elevation)
Use && to combine conditions. This finds mountains between
8000 and 9000 meters — the famous "eight-thousanders."
String Functions in FILTER
SELECT ?city ?cityLabel
WHERE {
?city wdt:P31 wd:Q515 ;
rdfs:label ?cityLabel .
FILTER(LANG(?cityLabel) = "en")
FILTER(STRSTARTS(?cityLabel, "New"))
}
LIMIT 20
String functions like STRSTARTS(), CONTAINS(), and
REGEX() let you filter by text patterns. The LANG()
function checks the language tag of a literal.
SELECT ?person ?personLabel
WHERE {
?person wdt:P31 wd:Q5 ;
wdt:P106 wd:Q82955 ;
rdfs:label ?personLabel .
FILTER(LANG(?personLabel) = "en")
FILTER(REGEX(?personLabel, "Einstein$"))
}
REGEX supports full regular expressions. The $ anchors the match to the
end of the string. Use "i" as a third argument for case-insensitive matching.
Existence Tests
SELECT ?person ?personLabel ?spouse ?spouseLabel
WHERE {
?person wdt:P31 wd:Q5 ;
wdt:P106 wd:Q901 .
OPTIONAL { ?person wdt:P26 ?spouse . }
FILTER(!BOUND(?spouse))
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
LIMIT 20
BOUND(?var) tests whether a variable has a value. Combined with OPTIONAL,
!BOUND(?var) finds items that lack a particular property.
Key Entities Used in Examples
| Entity | Description |
|---|---|
wd:Q5 | Human |
wd:Q515 | City |
wd:Q6256 | Country |
wd:Q8502 | Mountain |
wd:Q82955 | Politician |
wd:Q901 | Scientist |
wdt:P26 | Spouse |
wdt:P31 | Instance of |
wdt:P106 | Occupation |
wdt:P1082 | Population |
wdt:P2044 | Elevation |