Subqueries
Nest queries within queries. Subqueries let you compute intermediate results, apply aggregations, and structure complex logic in manageable pieces.
Understanding Subqueries
Subqueries are complete SELECT queries nested inside another query's WHERE clause. The inner query runs first, and its results become available to the outer query. This is essential when you need to aggregate before joining, or limit before expanding.
Subquery for Limiting
SELECT ?country ?countryLabel ?capital ?capitalLabel ?population
WHERE {
{
SELECT ?country ?population WHERE {
?country wdt:P31 wd:Q6256 ;
wdt:P1082 ?population .
}
ORDER BY DESC(?population)
LIMIT 10
}
?country wdt:P36 ?capital .
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
The subquery finds the 10 most populous countries. The outer query then fetches their capitals. This is more efficient than fetching capitals for all countries and then sorting/limiting—the limit happens before the join.
Subquery with Aggregation
SELECT ?country ?countryLabel ?cityCount
WHERE {
{
SELECT ?country (COUNT(?city) AS ?cityCount) WHERE {
?city wdt:P31 wd:Q515 ;
wdt:P17 ?country .
}
GROUP BY ?country
HAVING(?cityCount > 100)
}
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
ORDER BY DESC(?cityCount)
Subqueries are essential when combining aggregation with non-aggregated data. The inner query counts cities per country and filters for those with over 100. The outer query adds labels for the countries that passed the filter.
Finding Extremes per Group
SELECT ?country ?countryLabel ?mountain ?mountainLabel ?elevation
WHERE {
{
SELECT ?country (MAX(?elev) AS ?elevation) WHERE {
?m wdt:P31 wd:Q8502 ;
wdt:P17 ?country ;
wdt:P2044 ?elev .
}
GROUP BY ?country
}
?mountain wdt:P31 wd:Q8502 ;
wdt:P17 ?country ;
wdt:P2044 ?elevation .
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
ORDER BY DESC(?elevation)
LIMIT 20
This pattern finds the maximum value per group, then joins back to find which item has that value. The subquery finds each country's max elevation, and the outer query finds the mountain matching that country-elevation pair.
Key Entities Used in Examples
| Entity | ID | Description |
|---|---|---|
| country | wd:Q6256 | Sovereign state |
| city | wd:Q515 | Large human settlement |
| mountain | wd:Q8502 | Large landform rising above terrain |
| population | wdt:P1082 | Number of inhabitants |
| capital | wdt:P36 | Seat of government |
| country (property) | wdt:P17 | Sovereign state of location |
| elevation | wdt:P2044 | Height above sea level |