Query data
Return distinct values
Use DISTINCT when the result needs unique combinations instead of every matching row.
8 minute lesson
Use DISTINCT when the result needs unique values instead of every matching row:
SELECT DISTINCT country
FROM users
ORDER BY country;
If 50 users live in Italy and 30 live in Denmark, the result contains two country rows.
With several selected columns, uniqueness applies to the complete combination:
SELECT DISTINCT country, city
FROM users;
Italy, Rome and Italy, Milan remain separate. Adding a unique column such as id would make every row distinct and remove the benefit.
Several NULL values normally appear as one distinct result value. This is result-set behavior; it does not mean ordinary comparisons consider NULL equal to NULL.
Be suspicious when DISTINCT is added only to hide duplicates after a join. The join may be matching more related rows than expected, or the schema may be missing a uniqueness rule. Removing visible duplicates does not fix an incorrect total or an accidental many-to-many relationship.
DISTINCT can require sorting or hashing a large result. Use it because the question asks for unique combinations, not as a default decoration.
Your action is to run DISTINCT on one column, two columns, and two columns including a unique ID. Predict the number of result rows before each query.
Lesson completed