DISTINCT

Also known as: SELECT DISTINCT

On this page 7

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 rowsResult with DISTINCTExplanation
(‘Oslo’), (‘Oslo’)One row: ‘Oslo’Identical values collapse
(‘Oslo’, 1), (‘Oslo’, 2)Both rows keptSecond column differs
(NULL), (NULL)One row: NULLNULLs are treated as not distinct
(‘oslo’), (‘Oslo’)Depends on collationCase-insensitive collations merge them
(1.0), (1.00)Usually one rowNumeric values compare by value
How DISTINCT treats different value situations

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.

FormExampleEffect
SELECT DISTINCTSELECT DISTINCT country FROM customersUnique rows of the result
Aggregate with DISTINCTCOUNT(DISTINCT customer_id)Aggregates only unique values
DISTINCT ONSELECT DISTINCT ON (customer_id) ...First row per key, PostgreSQL only
IS DISTINCT FROMa IS DISTINCT FROM bNULL-safe comparison operator
Forms of DISTINCT in SQL

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.

ConstructPrimary purposeDeduplicatesAllows aggregates
SELECT DISTINCTList unique combinationsYes, whole rowNo per-group aggregates
GROUP BYSummarize per groupYes, by grouping keyYes, with HAVING filters
UNIONCombine two queriesYes, across both inputsOnly inside each input
UNION ALLCombine without checksNoOnly inside each input
Comparison of deduplication approaches

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.

SymptomUnderlying causeBetter approach
Duplicates after a joinOne-to-many join not intendedUse EXISTS or a semi-join
SUM too large despite DISTINCTAggregation before deduplicationAggregate in a subquery or CTE first
Slow report queryDISTINCT over many wide columnsDeduplicate keys, then join details
Need latest row per keyDISTINCT cannot choose a rowUse ROW_NUMBER or DISTINCT ON
Common DISTINCT misuse and better alternatives

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.