What does DISTINCT do?
SQLLevel: FoundationFundamentals (Easy)
What does DISTINCT do?
Hints
- Define one output row and the source-table keys.
- Check duplicates, NULLs and the order of filtering and aggregation.
Answer
DISTINCT removes duplicate rows from the result set. It operates on the combination of all selected columns.
-- Returns unique departments
SELECT DISTINCT department FROM employees;
-- Returns unique combinations of department AND job_title
SELECT DISTINCT department, job_title FROM employees;
DISTINCT can be expensive because the database usually has to sort or hash the entire result set to find duplicates. For large tables, it's worth asking whether you actually need it or whether your query logic can avoid duplicates in the first place.
Common wrong answer: Thinking DISTINCT applies only to the first column listed.
Source and licence: SQL Interview Questions — Arda Kocadoru · MIT