HAVING
Filter groups after aggregation. HAVING applies conditions to aggregate results, keeping only groups that meet your criteria.
Understanding HAVING
HAVING filters the results of GROUP BY based on aggregate values. While FILTER operates on individual rows before grouping, HAVING operates on groups after aggregation.
| Clause | When it applies | Use case |
|---|---|---|
FILTER | Before grouping | Filter individual items |
HAVING | After grouping | Filter based on aggregate values |
Basic HAVING Examples
SELECT ?country ?countryLabel (COUNT(?city) AS ?cityCount)
WHERE {
?city wdt:P31 wd:Q515 ;
wdt:P17 ?country .
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
GROUP BY ?country ?countryLabel
HAVING (COUNT(?city) > 1000)
ORDER BY DESC(?cityCount)
This query groups cities by country and uses HAVING to keep only countries with more than 1000 cities. The HAVING clause references the same aggregate expression used in SELECT.
SELECT ?author ?authorLabel (COUNT(?work) AS ?workCount)
WHERE {
?work wdt:P50 ?author .
?author wdt:P31 wd:Q5 .
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
GROUP BY ?author ?authorLabel
HAVING (COUNT(?work) >= 100)
ORDER BY DESC(?workCount)
LIMIT 20
Find the most prolific authors by filtering for those with at least 100 works.
The HAVING clause uses >= to include authors with exactly 100 works.
HAVING with Multiple Conditions
SELECT ?continent ?continentLabel
(COUNT(?country) AS ?countryCount)
(SUM(?population) AS ?totalPop)
WHERE {
?country wdt:P31 wd:Q6256 ;
wdt:P30 ?continent ;
wdt:P1082 ?population .
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
GROUP BY ?continent ?continentLabel
HAVING (COUNT(?country) > 10 && SUM(?population) > 100000000)
ORDER BY DESC(?totalPop)
HAVING can combine multiple conditions using logical operators (&& for AND,
|| for OR). This query finds continents with both many countries and large
total populations.
HAVING with Different Aggregates
SELECT ?country ?countryLabel (AVG(?elevation) AS ?avgElevation)
WHERE {
?mountain wdt:P31 wd:Q8502 ;
wdt:P17 ?country ;
wdt:P2044 ?elevation .
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
GROUP BY ?country ?countryLabel
HAVING (AVG(?elevation) > 3000)
ORDER BY DESC(?avgElevation)
LIMIT 15
This query finds mountainous countries by filtering for those where the average elevation of mountains exceeds 3000 meters. HAVING works with any aggregate function.
Key Entities Used in Examples
| Entity | Description |
|---|---|
wd:Q5 | Human |
wd:Q515 | City |
wd:Q6256 | Country |
wd:Q8502 | Mountain |
wdt:P17 | Country (location) |
wdt:P30 | Continent |
wdt:P31 | Instance of (type) |
wdt:P50 | Author |
wdt:P1082 | Population |
wdt:P2044 | Elevation above sea level |