Query data
Return distinct values
Use DISTINCT when the result needs unique combinations instead of every matching row.
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, not 80.
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 treat NULL equal to NULL. If you need to count NULLs separately, use an aggregate instead of DISTINCT.
Be suspicious when DISTINCT is added only to hide duplicates after a join. The join may be matching more related rows than you expect. 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. That costs time and memory on big tables. Use it because the question asks for unique combinations, not as a default decoration on every query.
If you need a count of unique values instead of the values themselves, COUNT(DISTINCT country) returns one number. That is often cheaper than returning every distinct row and counting them in application code.
Try this on your own: run DISTINCT on one column, two columns, and two columns including a unique ID. Predict the number of result rows before each query, then run them and compare.
Lesson completed