What does the 'DISTINCT' keyword do in SQL queries?
Instruction: Explain the purpose of the DISTINCT keyword and provide an example query.
Updated
Official answer
SELECT DISTINCT removes duplicate tuples from the selected result columns. It does not modify stored rows or create a uniqueness constraint.
For PostgreSQL:
WITH visits(user_id, city) AS (
VALUES (1,'Paris'), (1,'Paris'), (1,'Rome'), (2,NULL), (2,NULL)
)
SELECT DISTINCT user_id, city
FROM visits
ORDER BY user_id, city NULLS LAST;
The result is (1,Paris), (1,Rome), (2,NULL). Uniqueness applies to the combination, not to each column separately; duplicate NULL-containing result tuples collapse here.
Use DISTINCT when that result grain is intended. It can hide a mistaken join or discard meaningful repeated events if applied without understanding the data. SUM(DISTINCT amount) sums distinct numeric values, not necessarily distinct purchases. Deduplication also has execution cost, so inspect the plan for large results. Enforce a stored business-key invariant with the appropriate constraint rather than relying on SELECT DISTINCT in reports.