Stop 02 · Basic SELECT QueriesTopics · 6/8

SELECT DISTINCT

Part of the SQL Roadmap

In short

Want to know which cities your customers come from? Selecting city gives you every row, with Mumbai repeated hundreds of times. DISTINCT collapses repeats into one.

DISTINCT removes duplicate rows from the result, based on all selected columns together, not just the first one.

The jaadu sorts a pile of postage stamps on a table, placing one of each design into a neat album and sliding the duplicates aside.

Think of it like this

Sorting a stamp collection

You tip out a shoebox of postal stamps and keep just one of each design, setting the duplicates aside. You learn what kinds you have, not how many. DISTINCT does that with rows: one copy of each unique combination stays.

Watch it happen

SELECT DISTINCT city

Mumbai
0
Pune
1
Mumbai
2
Delhi
3
Pune
4
Mumbai
5

1/4SELECT city gives six rows, with lots of repeats.

The big ideas

What you need to know

Removes duplicate rows

DISTINCT goes right after SELECT and removes rows that are identical in every selected column.

Applies to all columns together

SELECT DISTINCT city, state treats (Pune, Maharashtra) as one combination, not just distinct cities.

Count unique values

COUNT(DISTINCT city) tells you how many unique cities there are, as a single number.

A symptom, sometimes

If you need DISTINCT to fix doubled rows after a join, the join is probably wrong. Fix the cause.

See it in code

Walk through the code

sql
1-- Which cities do customers live in?2SELECT DISTINCT city3FROM customers4ORDER BY city;5 6-- Unique city and state pairs7SELECT DISTINCT city, state8FROM customers;9 10-- How many unique cities?11SELECT COUNT(DISTINCT city) AS city_count12FROM customers;

1/3One row per city, sorted alphabetically.

DISTINCT works the same in PostgreSQL, MySQL and SQL Server. PostgreSQL also has DISTINCT ON for picking one row per group, which you'll meet later.

Save yourself the pain

Common mistakes

Oops

Writing SELECT DISTINCT city, name and expecting one row per city.

Do this instead

DISTINCT applies to the whole row. With name included, every customer is unique again.

Oops

Adding DISTINCT to every query "just in case".

Do this instead

It costs a sort or hash on every run and can hide real data problems. Use it when you mean it.

Your mission

Find the unique values

~15 min

Quick check

A table has rows (Pune, MH), (Pune, MH) and (Pune, KA). How many rows does SELECT DISTINCT city, state return?

Go deeper

  1. 1List the distinct cities in a customers table.
  2. 2Try DISTINCT on two columns and see how the result changes.
  3. 3Ask why duplicates exist before hiding them with DISTINCT.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge