How does the DISTINCT keyword work, and what are the performance considerations of using it?

Last updated 3 July 2026

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 SELECT list, not just the first one: DISTINCT a, b dedupes 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 DISTINCT to mask duplicates caused by a bad JOIN: fix the join instead.

    • For existence checks prefer EXISTS over SELECT DISTINCT, and use GROUP BY when 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
All SQL interview questions