CPCODELAB
SQL

DISTINCT — Removing Duplicates

5 min read

Eliminating Duplicates with DISTINCT

SELECT DISTINCT removes duplicate rows from the result. It operates on the entire row, so two rows are considered duplicates only if every selected column matches.

sql
-- List unique cities where students live
SELECT DISTINCT city FROM students ORDER BY city;

-- Unique category + price combinations
SELECT DISTINCT category, price FROM courses ORDER BY category;

DISTINCT can be expensive on large tables because the database must sort or hash all rows before deduplicating. If you only need a count of unique values, COUNT(DISTINCT column) is often faster than fetching all distinct rows.

Ready to test yourself?
Practice SQL— quiz & coding exercises