DISTINCT is the SQL keyword that removes duplicate rows from a query result, so that each unique combination of values in the selected columns appears only once. Written as SELECT DISTINCT, it is applied after the rows are filtered and projected but before sorting and row limits, and it can also appear inside aggregate functions, as in COUNT(DISTINCT customer_id).
In SQL, duplicates arise naturally from joins, from selecting only some columns of a table, and from data that was never constrained to be unique. DISTINCT answers the question which different values exist, but it carries a real processing cost and is frequently used to hide query mistakes rather than to express intent.
How DISTINCT determines duplicate rows
DISTINCT compares entire rows of the select list, not individual columns. Two rows count as duplicates only when every selected column holds equal values, so SELECT DISTINCT city, country keeps Paris in France and Paris in Texas as separate rows.
For this comparison, SQL treats NULL values as not distinct from each other, which means all NULLs in a column collapse into a single row. This differs from ordinary equality, where NULL = NULL evaluates to unknown, and it is one of the few places where the standard groups NULLs together, just as GROUP BY does.
| Input rows | Result with DISTINCT | Explanation |
|---|---|---|
| (‘Oslo’), (‘Oslo’) | One row: ‘Oslo’ | Identical values collapse |
| (‘Oslo’, 1), (‘Oslo’, 2) | Both rows kept | Second column differs |
| (NULL), (NULL) | One row: NULL | NULLs are treated as not distinct |
| (‘oslo’), (‘Oslo’) | Depends on collation | Case-insensitive collations merge them |
| (1.0), (1.00) | Usually one row | Numeric values compare by value |
The collation of text columns therefore affects the outcome. Under a case-insensitive collation, common by default in SQL Server and MySQL, ‘Oslo’ and ‘oslo’ are one value, while PostgreSQL’s default collations treat them as different.
Syntax forms and where DISTINCT applies
DISTINCT appears in three main syntactic positions, each with a different scope. The keyword always applies to the whole select list, never to the single column written right after it, which is a widespread misreading of SELECT DISTINCT a, b.
| Form | Example | Effect |
|---|---|---|
| SELECT DISTINCT | SELECT DISTINCT country FROM customers | Unique rows of the result |
| Aggregate with DISTINCT | COUNT(DISTINCT customer_id) | Aggregates only unique values |
| DISTINCT ON | SELECT DISTINCT ON (customer_id) ... | First row per key, PostgreSQL only |
| IS DISTINCT FROM | a IS DISTINCT FROM b | NULL-safe comparison operator |
DISTINCT ON is a PostgreSQL extension that keeps the first row for each key according to the ORDER BY clause, a compact way to fetch the latest order per customer. The IS DISTINCT FROM predicate shares the word but is a comparison operator, not a deduplication step. Other databases solve the per-key case with a window function such as ROW_NUMBER().
DISTINCT compared with GROUP BY and UNION
DISTINCT, GROUP BY and UNION can all produce unique rows, and query optimizers often execute them with the same plan. The choice between them should follow intent: DISTINCT lists unique values, GROUP BY computes per-group aggregates, and UNION combines result sets.
| Construct | Primary purpose | Deduplicates | Allows aggregates |
|---|---|---|---|
| SELECT DISTINCT | List unique combinations | Yes, whole row | No per-group aggregates |
| GROUP BY | Summarize per group | Yes, by grouping key | Yes, with HAVING filters |
| UNION | Combine two queries | Yes, across both inputs | Only inside each input |
| UNION ALL | Combine without checks | No | Only inside each input |
SELECT DISTINCT a, b FROM t and SELECT a, b FROM t GROUP BY a, b return the same rows, and most engines plan them identically. A practical rule follows from UNION: when inputs cannot overlap, UNION ALL avoids an unnecessary deduplication step that plain UNION would perform.
Performance cost of removing duplicates
Deduplication requires the database to compare every result row with the others, which it does by sorting or by hashing. A sort-based plan orders the rows and drops adjacent duplicates, costing roughly n log n comparisons; a hash aggregate builds an in-memory table of seen values and runs in about linear time when the table fits in memory.
When the working set exceeds available memory, both strategies spill to temporary disk storage, and queries can slow down dramatically. An index whose leading columns match the select list lets the optimizer read values in order and skip the sort entirely, and some engines can perform a skip scan or loose index scan that jumps between distinct keys.
- DISTINCT on a primary key or unique column is redundant, and many optimizers remove it automatically.
- DISTINCT on wide rows with long text columns is expensive because every byte takes part in the comparison.
- DISTINCT combined with ORDER BY requires the sort columns to appear in the select list in standard SQL.
When DISTINCT signals a query problem
Experienced reviewers treat an unexplained DISTINCT as a warning sign of a faulty join. When a JOIN multiplies rows because one side has several matches, adding DISTINCT removes the visible duplicates but leaves the row explosion and its cost in place, and it can silently corrupt aggregates.
| Symptom | Underlying cause | Better approach |
|---|---|---|
| Duplicates after a join | One-to-many join not intended | Use EXISTS or a semi-join |
| SUM too large despite DISTINCT | Aggregation before deduplication | Aggregate in a subquery or CTE first |
| Slow report query | DISTINCT over many wide columns | Deduplicate keys, then join details |
| Need latest row per key | DISTINCT cannot choose a row | Use ROW_NUMBER or DISTINCT ON |
The guiding principle is to express the actual question. If the query asks whether a customer has any orders, EXISTS states that directly and stops at the first match, while a join followed by DISTINCT processes every order before throwing most rows away.
Understanding it simply
Imagine a guest list where some names were written down twice. DISTINCT tells the database to show each entry only once, so the list contains every guest but no repeats.
It looks at the whole line, though. If the list has both a name and a city, the same name with two different cities still appears twice. The main thing to remember is that removing repeats takes extra work, and repeats sometimes mean the question itself was asked in the wrong way.
Applied in practice
A data analyst at a subscription software company needs the number of customers who opened a support ticket last quarter. The first query joins customers to tickets and counts rows, returning 18,400, which is clearly too many because many customers filed several tickets.
Rewriting it as COUNT(DISTINCT customer_id) on the tickets table returns 6,950 unique customers, the correct figure. For the follow-up report listing those customers with their account details, the analyst replaces a join plus SELECT DISTINCT with a WHERE EXISTS subquery, which cuts the query time from about 40 seconds to under 3 seconds on the reporting database because the engine no longer sorts the multiplied ticket rows.