SQL DISTINCT: How Deduplication Works and How to Optimize It
This article explains how SQL DISTINCT actually works and how to use it efficiently. It clarifies what DISTINCT compares, how NULL values are handled, and why it cannot replace per-group row selection. It then covers the main execution strategies—sort-based deduplication, hash-based deduplication, and elimination via unique indexes—along with the relationship between DISTINCT, GROUP BY, and set operations. The final section lists practical guidelines and common anti-patterns for correctness and performance.
1. Why Explicit Deduplication Is Needed
The relational model is built on set semantics, but many real-world tables do not satisfy the ideal assumption of a unique primary key. Log detail tables may contain duplicate writes, dimension tables may hold multiple versions of a record, externally imported data may lack constraints, and joins can multiply rows through one-to-many relationships. When the analytical question is “which distinct values exist” rather than “how many records are there,” you need an explicit operator to collapse duplicate rows. That is the purpose of DISTINCT.
It is important to note that deduplication is not a data repair mechanism. DISTINCT only affects the result set returned by the current query; it does not change the data in the underlying storage. If duplicates come from a defect in the write path, the correct fix belongs in data ingestion and modeling, not in a DISTINCT clause added to every query as a fallback. Otherwise, data quality problems stay hidden, and the cost is continuous waste of compute resources.
2. What DISTINCT Actually Deduplicates
The most common misunderstanding is treating DISTINCT as column-by-column deduplication. In fact, DISTINCT applies to the entire column list in the SELECT clause, and the comparison target is the value combination formed by those columns—conceptually, the whole projected row.
-- Return the distinct combinations of (dept_id, job_level)SELECT DISTINCT dept_id, job_levelFROM employee;
In this example, two rows are considered different if either dept_id or job_level differs. If you want to keep only one row per department, DISTINCT cannot do it, because columns not listed in SELECT do not participate in the comparison and the database will not decide which row to keep for you. This kind of requirement is “pick a representative row after grouping” and should be expressed with a window function:
SELECT dept_id, employee_name, salaryFROM (SELECT dept_id, employee_name, salary,ROW_NUMBER() OVER (PARTITION BY dept_id ORDER BY salary DESC) AS rnFROM employee) tWHERE rn = 1;
Another frequent pitfall is NULL. Most databases treat multiple NULLs as identical in DISTINCT comparisons, so only one NULL row appears in the result. This differs from the rule in some join and comparison contexts where NULL is not equal to any value, including another NULL. Logic that depends on NULL semantics must confirm this behavior in advance.
Also note the restrictions when DISTINCT is combined with aggregation. COUNT(DISTINCT col) is valid: it counts the number of distinct values in that column and ignores NULL. DISTINCT COUNT(col) is invalid in most implementations. To count distinct combinations of multiple columns, build a subquery and aggregate in the outer query:
SELECT COUNT(*) AS combo_cntFROM (SELECT DISTINCT dept_id, job_level FROM employee) t;
3. Execution Mechanisms: Sort-Based and Hash-Based Deduplication
The database does not literally compare rows one by one. It chooses a deduplication strategy, typically one of two kinds.
Sort-based deduplication first sorts by the projected columns so that identical combinations become physically adjacent, then scans linearly and discards any record equal to the previous one. Its advantages are controlled memory usage, the ability to reuse an existing index order directly, and the fact that it also satisfies a subsequent ORDER BY. Its drawbacks are the O(n log n) cost of sorting itself and the temporary space consumed by a full sort.
Hash-based deduplication computes a hash value for the projected columns and inserts it into a hash table. On a collision, the full value is checked a second time; if the key already exists, the row is discarded. Its average complexity is close to O(n), which makes it friendlier to unordered data. The cost is that the hash table must stay in memory, and when memory is insufficient it spills to temporary storage. In extreme cases this degrades into repeated disk writes and performance drops sharply. When the key columns are long or there are many combination columns, the overhead of building and comparing hash keys also rises noticeably.
Optimization via a unique index: when the queried column combination is fully covered by a unique index or primary key, the optimizer can confirm that the result is inherently unique and remove the deduplication operator entirely. This is the ideal case, where deduplication costs nothing. The lesson for modeling is direct: declaring the keys that are truly unique in business terms as constraints is far more worthwhile than repeatedly deduplicating in queries.
4. Relationship with GROUP BY and Set Operations
SELECT DISTINCT a, b FROM t and SELECT a, b FROM t GROUP BY a, b return the same result when only the grouping columns are output, but their semantic intent differs. The former expresses “deduplicate after projection,” while the latter expresses “group by dimensions.” Once an aggregate function appears in SELECT, the two are no longer interchangeable. For readability, use DISTINCT when no aggregation is needed because it matches the intent more closely; use GROUP BY when you need aggregation or need to filter groups with HAVING.
Set operations also imply deduplication. A union excludes duplicate rows by default; use the full union semantics when duplicates must be retained. Difference and intersection are likewise based on set semantics. This means deduplication may occur in several places within a complex query, so when reading an execution plan you should confirm it layer by layer to avoid redundant work.
5. Best Practices and Common Anti-Patterns
- Fix the model and constraints first, so uniqueness is guaranteed by the data definition rather than patched by queries.
- Before using DISTINCT, confirm that the column list really forms the business unique key, so missing a column does not leave duplicates behind.
- Watch out for “JOIN first, DISTINCT later.” The row multiplication from a one-to-many join has already consumed all the compute and memory before deduplication happens; aggregating first or using an EXISTS semi-join is often cheaper.
- When deduplicating a large result set, check the operator chosen in the execution plan and the memory and temporary space metrics. If necessary, reduce the key size through pre-aggregation, partition pruning, or fewer projected columns.
- DISTINCT breaks result ordering. If the output must be ordered, write the sort clause explicitly and do not rely on incidental row order.
- On platforms that support window functions, prefer a window function for requirements such as “deduplicate and keep the latest row”; the semantics are clear and it usually needs only one scan.
6. Summary
DISTINCT is an operator with simple semantics but a wide impact: it deduplicates whole rows by the projected column combination, has a defined handling of NULL, and may be executed by sorting, by hashing, or omitted entirely thanks to a unique index. Understanding these three points helps you avoid correctness errors such as column-by-column deduplication, missing columns, and relying on row order, and avoid performance mistakes such as using deduplication as a data quality patch or amplifying rows through joins on large result sets. In data platform scenarios—whether data cleaning, metric definition validation, or ad hoc analysis—moving uniqueness constraints forward into modeling and ingestion, and writing queries that clearly express whether the intent is deduplication or grouping, is the approach that stays stable and cost-controlled over the long term.
