Aggregate
COUNT
Count the number of results. COUNT is the most common aggregate function, used to tally items, relationships, or any matching patterns.
Understanding COUNT
COUNT returns the number of items that match a pattern. Use COUNT(*)
to count all rows, or COUNT(?var) to count non-null values.
| Syntax | Description |
|---|---|
COUNT(*) | Count all matching rows |
COUNT(?var) | Count non-null values |
COUNT(DISTINCT ?var) | Count unique values |
Basic Counting
Count All Countries
SELECT (COUNT(?country) AS ?count)
WHERE {
?country wdt:P31 wd:Q6256 .
}
Count with DISTINCT
SELECT (COUNT(DISTINCT ?country) AS ?uniqueCountries)
WHERE {
?city wdt:P17 ?country .
?city wdt:P31 wd:Q515 .
}
COUNT with GROUP BY
Cities per Country
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
ORDER BY DESC(?cityCount)
LIMIT 10
Works per Author
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
ORDER BY DESC(?workCount)
LIMIT 10