SQL DISTINCT: Deduplication Principles and Query Optimization Practices

    This article explores the core principles of SQL DISTINCT for result set deduplication, detailing its implementation mechanisms, common pitfalls, and best practices for performance optimization.

    1. The Role of DISTINCT: Row-Level Deduplication in Result Sets

    DISTINCT is an optional modifier in the SELECT statement that operates on the final output result set rather than the physical storage of the database table. It does not modify the underlying data; instead, it eliminates duplicate rows during query execution, acting purely as a read-only logical operator.

    The basic syntax is as follows:

    1. SELECT [ALL | DISTINCT] column1 [, column2, ...]
    2. FROM table_name
    3. [WHERE conditions]
    4. [ORDER BY ...];

    Here, ALL is the default modifier, indicating that all rows (including duplicates) should be retained. DISTINCT requires the output rows to be unique based on the specified combination of columns. Omitting the column list is equivalent to selecting all columns.

    It is crucial to understand the semantic boundary: the deduplication granularity of DISTINCT applies to the combined values of all columns in the SELECT list, not individual columns. For example:

    1. -- Example table: sales(region, channel, amount)
    2. SELECT DISTINCT region, channel FROM sales;

    If either region or channel differs, the entire row is considered unique. Thus, the example above returns all unique combinations of “region and channel,” not a unique list of regions. If you only need unique values from a single column, you must select only that specific column.

    2. Three Typical Implementation Mechanisms and Trade-offs

    Database optimizers choose different physical deduplication strategies based on data volume, memory budget, and access paths.

    1. Sort-Based Deduplication. The input is first sorted by the target columns, followed by comparing adjacent rows for equality; if they match, duplicates are discarded. The advantage is controllable memory usage and streaming output capability. If the input is naturally ordered via an index or a preceding sort operator, the sorting overhead can be bypassed. The trade-off is the O(n log n) cost of sorting itself, along with temporary space consumption for large datasets.

    2. Hash-Based Deduplication. A hash key is constructed for the column combination. The database probes the hash table row by row; if it is the first occurrence, the row is output and registered. The amortized complexity is near-linear, making it generally superior for large result sets with low duplication rates. The risk lies in memory sensitivity: if the state table becomes too large, it spills to temporary storage, incurring extra I/O. Additionally, because hash results are unordered, the output sequence is unpredictable.

    3. Optimization via Unique Indexes or Constraints. When the queried columns are fully covered by a unique index, the index inherently guarantees key uniqueness. The optimizer can then omit the deduplication operator entirely and perform only an index scan. This is the most efficient path and a structural optimization worth prioritizing during the design phase.

    The selection logic can be summarized as follows: whether the input is already sorted, whether available memory is sufficient, the duplication rate, and whether a unique index can be hit—these four factors jointly determine the final execution plan.

    3. Semantic Details and Common Pitfalls

    Handling NULLs. In mainstream databases, deduplication comparisons follow the rule that “NULLs are treated as equal to each other,” meaning multiple NULL rows are merged into one. This differs from how NULLs behave in WHERE clause comparisons (where they return unknown), which can cause misunderstandings during data cleansing.

    Column Constraints with ORDER BY. Most databases require that expressions appearing in the ORDER BY clause must be included in the DISTINCT column set; otherwise, an error is thrown, as the sorting basis becomes indeterminate after deduplication.

    Combination with Aggregate Functions. Deduplication can be pushed down into aggregates to count non-repeating cardinalities:

    1. SELECT COUNT(DISTINCT channel) AS channel_cnt FROM sales;

    Note that the multi-column format COUNT(DISTINCT a, b) is not supported by all databases, so compatibility considerations are necessary for cross-dialect development.

    Relationship with GROUP BY. In scenarios without aggregate columns or HAVING clauses, the two are equivalent:

    1. SELECT DISTINCT region, channel FROM sales;
    2. SELECT region, channel FROM sales GROUP BY region, channel;

    The difference lies in intent and extensibility: GROUP BY can carry aggregate functions and HAVING for grouped statistics, meaning “grouping.” DISTINCT means “output unique rows,” making it more lightweight and direct. For readability, choose based on your actual intent rather than relying on the optimizer’s equivalent rewrites.

    Alternative Rewriting in Subqueries. When deduplication is solely used to eliminate the amplification effect of join paths, expressing it using semi-join semantics is more accurate and optimization-friendly:

    1. -- Recommended: Clear semantics, avoids intermediate result bloat
    2. SELECT o.order_id FROM orders o
    3. WHERE EXISTS (SELECT 1 FROM items i WHERE i.order_id = o.order_id);

    4. Performance Optimization Practices

    • Filter Early: Push WHERE conditions as close to the data source as possible to reduce the input size entering the deduplication operator.
    • Streamline Column Lists: Avoid SELECT *. The fewer columns involved in deduplication, the narrower the hash state and sort keys.
    • Leverage Partitioning and Indexes: Use partition pruning to reduce scan volume, and utilize covering indexes to transform deduplication into an ordered scan.
    • Push Forward to ETL Phase: For dimensional data with stable duplication rates, complete pre-aggregation or materialization during the data processing layer, allowing the query side to read unique results directly.
    • Distinguish “Unique Values” from “Latest Row per Group”: The latter requires retaining other columns, which DISTINCT cannot express. Window functions should be used instead:
    1. SELECT * FROM (
    2. SELECT s.*, ROW_NUMBER() OVER (PARTITION BY region, channel ORDER BY amount DESC) AS rn
    3. FROM sales s
    4. ) t WHERE rn = 1;
    • Ultra-Large-Scale Cardinality Statistics: When only approximate cardinality is needed and data volume is massive, approximate deduplication algorithms based on probabilistic sketches can be used, trading a controlled margin of error for significant reductions in memory and time.
    • Monitor Temporary Space and Parallelism: Both sort and hash deduplication consume temporary storage. It is necessary to monitor spill situations and set parallelism levels appropriately.

    5. Typical Application Scenarios

    DISTINCT is commonly used in four scenarios: first, enumerating dimension values before statistical analysis to ensure completeness; second, data cleansing and quality validation by comparing row counts before and after deduplication to identify abnormal duplication rates; third, building a unique dimension list before joining with fact tables to prevent join amplification; and fourth, verifying reporting metrics by using COUNT(DISTINCT) to check whether the uniqueness constraint of a business primary key has been violated.

    6. Checklist

    When writing queries containing DISTINCT, you can verify the following in sequence: do the deduplication columns cover the business uniqueness definition? Are there unnecessary columns included? Can a unique index be hit? Should it be rewritten using GROUP BY or a semi-join? Are the sort fields valid? Is the temporary space sufficient given the data scale? By considering both semantic correctness and execution efficiency, deduplication can evolve from a “post-event remedy” into an integral part of database design.