DISTINCT
Eliminate duplicate rows from query results. DISTINCT ensures each combination of values appears only once, cleaning up results when entities match multiple patterns.
Understanding DISTINCT
DISTINCT removes duplicate rows from query results. This is especially useful when entities have multiple values for a property (like multiple occupations or citizenships), which would otherwise produce repeated rows.
Basic DISTINCT Examples
SELECT DISTINCT ?country ?countryLabel
WHERE {
?person wdt:P166 ?award .
?award wdt:P31 wd:Q7191 .
?person wdt:P27 ?country .
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
ORDER BY ?countryLabel
Without DISTINCT, countries with many Nobel laureates would appear multiple times. The query finds Nobel Prize winners (P166 award of instance Q7191), gets their citizenship (P27), and returns each unique country once.
SELECT DISTINCT ?genre ?genreLabel
WHERE {
?film wdt:P57 wd:Q25191 ;
wdt:P136 ?genre .
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
This query finds all films directed by Steven Spielberg (Q25191) and returns each unique genre only once. Since a director makes many films in the same genre, DISTINCT prevents repeated genre entries.
DISTINCT with Multiple Variables
SELECT DISTINCT ?occupationLabel ?countryLabel
WHERE {
?person wdt:P106 ?occupation ;
wdt:P27 ?country .
?occupation wdt:P31 wd:Q28640 .
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
LIMIT 100
DISTINCT applies to the entire row. This query finds professions (occupations that are instance of profession Q28640) paired with countries, returning each unique combination once even if many people share that occupation-country pair.
When to Use DISTINCT
Use DISTINCT when: (1) entities can have multiple values for a property you're querying, (2) you only need to know what values exist, not how many times they appear, or (3) intermediate joins produce unwanted duplicates. Avoid DISTINCT when you need counts, as it may hide valuable frequency information.
Key Entities Used in Examples
| Entity | ID | Description |
|---|---|---|
| Nobel Prize | wd:Q7191 | Set of annual international awards |
| Steven Spielberg | wd:Q25191 | American film director |
| profession | wd:Q28640 | Vocation requiring training |
| award received | wdt:P166 | Award or honor received |
| country of citizenship | wdt:P27 | Country of legal citizenship |
| director | wdt:P57 | Director of a film or show |
| genre | wdt:P136 | Creative genre of work |
| occupation | wdt:P106 | Person's job or profession |