Aggregate

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.

ClauseWhen it appliesUse case
FILTERBefore groupingFilter individual items
HAVINGAfter groupingFilter based on aggregate values

Basic HAVING Examples

Countries with Many Cities
Run ↗
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.

Prolific Authors
Run ↗
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

Countries with Population Constraints
Run ↗
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

Countries with High Average Elevation
Run ↗
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

EntityDescription
wd:Q5Human
wd:Q515City
wd:Q6256Country
wd:Q8502Mountain
wdt:P17Country (location)
wdt:P30Continent
wdt:P31Instance of (type)
wdt:P50Author
wdt:P1082Population
wdt:P2044Elevation above sea level