How does the DISTINCT keyword work, and what are the performance considerations of using it?
Last updated
DISTINCT removes duplicate rows from a result set, returning only unique combinations of the selected columns. It's convenient but can be costly because the database must compare and deduplicate every row, usually via a sort or hash.
How it works:
Applies across all columns in the
SELECTlist, not just the first one:DISTINCT a, bdedupes on the pair.Treats multiple
NULLs as equal, so they collapse to one.
Performance considerations:
Requires a sort or hash aggregation over the full result: extra CPU and memory, possibly spilling to disk on large sets.
An index on the deduplicated columns can let the planner avoid a sort.
Watch out for:
Using
DISTINCTto mask duplicates caused by a badJOIN: fix the join instead.For existence checks prefer
EXISTSoverSELECT DISTINCT, and useGROUP BYwhen you also need aggregates.
- https://hyring.com/jobseeker-toolkit/interview-questions/technical/sql
- https://medium.com/@workwithalam/distinct-vs-group-by-understanding-the-real-difference-in-sql-86ec483a78f3
- https://medium.com/@nile.bits/understanding-the-power-of-distinct-in-sql-server-queries-aaf4be75de1f
- https://dev.to/jignect_technologies/sql-queries-execution-order-29ae
- https://dev.to/mrpercival/optimizing-sql-queries-1n1c
- https://www.postgresql.org/docs/current/multivariate-statistics-examples.html
- https://www.postgresql.org/docs/current/sql-select.html