SQL DISTINCT Explained: Semantics, Execution, and Deduplication Practices
This article breaks down SQL DISTINCT from first principles to production pitfalls: why query results contain duplicates, what DISTINCT actually applies to (the combined projection columns, not each column separately), how NULL values behave during deduplication, and the three physical implementations an optimizer may choose (sort-based, hash-based, and unique-index elimination). It also clarifies where DISTINCT ends and GROUP BY begins, covers common traps such as mixing DISTINCT with aggregates, join fan-out, and overly wide projections, and closes with practical guidance on controlling the cost of a stateful deduplication operator.
SQL DISTINCT Explained: Semantics, Execution, and Deduplication Practices
1. Where the Problem Starts: Why Result Sets Contain Duplicates
In a relational database, a table is a mathematical implementation of a set, but a query result is physically closer to a multiset. When the projection list does not include a key that uniquely identifies a row (a primary key or a column under a unique constraint), multiple source rows collapse into identical output rows. Typical cases include customer IDs that repeat across an orders table, error codes that recur in a log table, and category labels referenced many times in a dimension table.
This kind of duplication is not a data quality problem. It is the inevitable result of a projection that drops the distinguishing dimension. DISTINCT is the declarative mechanism that restores “uniqueness” semantics at the result-set level: it does not modify the underlying data, it only applies a single deduplication transformation at query output time.
2. Scope of the Semantics: What DISTINCT Actually Deduplicates
2.1 It applies to a column combination, not a single column
The most common misunderstanding is that SELECT DISTINCT a, b FROM t deduplicates a and b separately. The actual semantics are: the values of a and b are combined into a composite key, and that composite key is made unique. If any column in the composite key differs, the output row is considered different.
-- Deduplicate on the composite key: unique combinations of (dept_id, job_level)SELECT DISTINCT dept_id, job_level FROM employee;-- Equivalent form: same semantics, potentially different execution planSELECT dept_id, job_level FROM employee GROUP BY dept_id, job_level;
2.2 It applies to the entire projection list
The position of DISTINCT determines its scope. It only looks at the expressions listed in the SELECT clause, and has nothing to do with FROM, WHERE, or GROUP BY. So SELECT DISTINCT a FROM t WHERE ... means “filter first, then deduplicate”, not “deduplicate first, then filter”. Understanding this order is the key to diagnosing “why is the result still duplicated after I added DISTINCT”.
2.3 Relationship with ALL
Most dialects support SELECT [ALL | DISTINCT], where ALL is the default modifier meaning all rows are kept. The only value of writing ALL explicitly is self-documentation for readability; its execution semantics are identical to omitting it.
2.4 How NULL values participate in deduplication
Deduplication comparison follows value-comparison semantics, and NULL is treated as an independent value category: multiple NULLs collapse into a single row after deduplication, and NULL is not equal to any non-NULL value. This means the result of SELECT DISTINCT col contains at most one NULL row, which must be anticipated in advance when doing data profiling.
3. Execution Mechanics: Three Main Implementation Paths
There is no single universal “deduplication operator” in databases. The optimizer picks the lowest-cost physical implementation among several options.
Sort-based deduplication: the input is first sorted by the projection columns, then scanned linearly, and adjacent equal rows are reduced to one. Its advantage is controllable memory usage, and it can process the input as a stream directly by leveraging ordering provided by an index; the cost is the sorting overhead, which can be reused when an ORDER BY is present.
Hash-based deduplication: a hash table is built with the projection columns as the key, and the current row is discarded once an existing key is detected. Average complexity is close to linear, which makes it very friendly to unordered input; the cost is that the hash table must stay in memory, and when memory is insufficient it spills to temporary storage, triggering extra disk reads and writes.
Unique index optimization: when the projection list happens to cover all columns of a unique constraint or unique index, the optimizer can determine that the result is naturally unique and skip the deduplication operator entirely. This is the ideal case, and it is where the habit of “making the query cover an index” pays off.
Which path is chosen is usually not under the developer’s direct control, but you can indirectly lower the optimizer’s decision cost by narrowing the projection columns, avoiding wrapping functions around projected columns, and keeping columns in their native types.
4. The Boundary Between DISTINCT and GROUP BY
The two are equivalent in result when there is no aggregate function and the projection columns are exactly the same, but their design intent differs: GROUP BY expresses “group and compute”, while DISTINCT expresses “make unique after projection”. The differences show up in three places:
- They are not interchangeable when an aggregate function is involved.
GROUP BYcan be combined with aggregations such as counting and summing; DISTINCT cannot. - Their behavior when combined with window functions and sorting differs. DISTINCT compresses rows first and then participates in subsequent logic; GROUP BY results also take shape first, but the semantics of the grouping keys are more explicit.
- Readability and intent differ. Use DISTINCT when you only need uniqueness, it is more direct; use GROUP BY when you need to aggregate by dimension, it is more accurate.
Engineering advice: do not use DISTINCT to “cover up” grouping logic that should be expressed by GROUP BY, and do not use GROUP BY to simulate simple deduplication. A semantic mismatch will mislead later maintainers about the query’s intent.
5. Common Pitfalls and How to Avoid Them
Mixing DISTINCT with aggregate functions. COUNT(DISTINCT col) is legal and common, and it counts the number of distinct non-NULL values; but SUM(DISTINCT col) is a logic error in most scenarios, because it discards duplicate values before summing and the result loses business meaning.
Data amplification from joining before deduplicating. Cartesian-style expansion from a multi-table join followed by deduplication usually means a missing join condition or a granularity mismatch. The correct approach is to aggregate or deduplicate at the right granularity first, then perform the join.
Wide projections that make deduplication ineffective. When the projection includes an almost unique column (such as an auto-increment ID or a timestamp), DISTINCT effectively removes no rows yet still pays the full cost of the deduplication operator. In that case, reconsider whether the projection list contains columns that should not be there.
Filtering on a deduplicated result inside WHERE. Because of the logical execution order, you cannot apply a filter directly to the result of DISTINCT within the same query level; you need a subquery or a common table expression to express the layers.
WITH unique_pairs AS (SELECT DISTINCT dept_id, job_level FROM employee)SELECT dept_id, COUNT(*) AS level_countFROM unique_pairsGROUP BY dept_id;
6. Performance and Capacity: Practical Points
Deduplication is a stateful operator, and its resource consumption depends on both “the number of distinct output values” and “the width of a single row”, not on the input row count alone. Actionable optimization directions include: project only the columns the analysis truly needs; make filter conditions take effect as early as possible to shrink the input entering the deduplication stage; build appropriate indexes on frequently deduplicated columns so the optimizer has a chance to take the ordered streaming path; and for very large result sets, evaluate whether deduplication can be done in the application layer or in a distributed computing engine to avoid memory pressure on a single database.
In cloud environments, deduplicated intermediate results can be written to object storage and then analyzed a second time with a containerized computing platform or a data-warehouse-style service, while log services and monitoring alerts are used to observe slow queries and temporary space usage. General-purpose capabilities from Baidu AI Cloud (such as object storage, container platforms, log services, and monitoring alerts) can serve as infrastructure options for hosting this kind of analytical workload; refer to the official documentation for specific specifications and pricing.
7. Summary
The essence of DISTINCT is a declarative result-set uniquification transformation. Its target is the combined value of the projected columns, and at execution time the optimizer chooses among three paths: sort-based deduplication, hash-based deduplication, and index-based elimination. Mastering its semantic boundaries, clarifying its division of labor with GROUP BY, and avoiding pitfalls such as wide projections, granularity mismatches, and aggregate misuse is what lets you keep results correct while controlling query cost in statistical analysis, data cleansing, and report building.
