Explain it simply
Explain it simply
Ask a shop with hundreds of customers "which countries have we shipped to?" and simply selecting every customer's country shows Germany ten times and Mexico eight times. SELECT DISTINCT collapses duplicate rows into one and returns each different value only once.
It answers "what kinds exist?" questions: the country list in a filter dropdown, a blog's tag list, the set of product categories. It never changes the data in the table; it only trims the result it returns.
Problem → Why → Solution
The problem: the dropdown lists countries twice
A developer loads the options for a country filter dropdown. The first query returns one row per customer, so Germany and Mexico each appear twice. Adding DISTINCT fixes it, but the second query also selects city, and Germany is duplicated again. DISTINCT is not broken.
SELECT country FROM customers; -- Germany, Mexico, Mexico, ... repeated
SELECT DISTINCT country FROM customers; -- each country once
SELECT DISTINCT country, city -- Germany twice again:
FROM customers; -- (Germany, Berlin), (Germany, Mannheim)Why does Germany come back twice?
DISTINCT does not look at columns one by one; it compares whole rows made of every column in the SELECT list. (Germany, Berlin) and (Germany, Mannheim) are different rows, so both stay. If the dropdown needs only countries, the SELECT list must contain only country.
Core concept: DISTINCT compares complete rows
PostgreSQL applies DISTINCT after WHERE has filtered the rows and the SELECT list has been computed. Two rows count as duplicates only when every column matches, and then just one of them is kept. Each extra column therefore changes what "duplicate" means: with country alone you get a list of countries; with country and city you get a list of (country, city) pairs.
NULL handling differs from WHERE. In a WHERE clause NULL = NULL is never TRUE, but DISTINCT treats NULLs as "not distinct" from each other, so however many NULL rows exist, only one NULL row remains. psql prints NULL as an empty cell, so an empty line in the output is that NULL.
DISTINCT promises no order. PostgreSQL may remove duplicates by sorting or with a hash table, and a hash produces rows in any order. Add ORDER BY yourself. With SELECT DISTINCT, every ORDER BY expression must appear in the SELECT list; otherwise you get "for SELECT DISTINCT, ORDER BY expressions must appear in select list", because one collapsed country row may stand for many cities and PostgreSQL cannot know which city to sort by.
DISTINCT is not free: it has to sort or hash every row, which costs time on big tables. Using it to hide rows multiplied by a wrong JOIN only covers up the real bug.
SELECT DISTINCT country gives the same rows as SELECT country ... GROUP BY country, and PostgreSQL often runs both with the same plan. Reach for GROUP BY once you also need counts or sums per group, which a later lesson covers.
- Filter with WHERE
- Join selected columns into one key
- Keep one row per key
- Sort with ORDER BY
Inside the key, NULLs count as equal to each other.
General pattern
SELECT DISTINCT column_a, column_b
FROM table_name
WHERE condition
ORDER BY column_a, column_b;
SELECT COUNT(DISTINCT column_a) FROM table_name;
-- PostgreSQL only: one row per column_a
SELECT DISTINCT ON (column_a) column_a, column_b
FROM table_name
ORDER BY column_a, sort_key DESC;DISTINCT comes right after SELECT and applies to the whole column list. COUNT(DISTINCT ...) counts how many different values exist. DISTINCT ON is a PostgreSQL extension that keeps the first row of each group according to ORDER BY.
Example: a country list and a (country, city) list
Of the seven customers, two are in Germany, two in Mexico (same city) and two in the UK (both London), and Cactus Comidas has a NULL country. Comparing the two queries shows how the meaning of "duplicate" follows the column list.
CREATE TABLE customers (
customer_id integer PRIMARY KEY,
customer_name text NOT NULL,
city text,
country text
);
INSERT INTO customers VALUES
(1, 'Alfreds Futterkiste', 'Berlin', 'Germany'),
(2, 'Ana Trujillo', 'Mexico City', 'Mexico'),
(3, 'Antonio Moreno', 'Mexico City', 'Mexico'),
(4, 'Around the Horn', 'London', 'UK'),
(5, 'Blauer See Delikatessen', 'Mannheim', 'Germany'),
(6, 'Cactus Comidas', 'Buenos Aires', NULL),
(7, 'Consolidated Holdings', 'London', 'UK');SELECT DISTINCT country
FROM customers
ORDER BY country;
SELECT DISTINCT country, city
FROM customers
ORDER BY country, city;Code breakdown
- One column
SELECT DISTINCT countrySeven rows shrink to four different countries: Germany, Mexico, UK and one NULL. The empty line is Cactus Comidas's NULL country.
- ORDER BY
ORDER BY country;DISTINCT alone promises no order, so ORDER BY is added. PostgreSQL sorts NULL last in ascending order, which is why the empty line is at the bottom.
- Two columns
SELECT DISTINCT country, cityNow (country, city) pairs are compared: Germany appears twice, once with Berlin and once with Mannheim, while Mexico City and London appear once each.
- Sort keys
ORDER BY country, city;Both sort columns appear in the SELECT list, so this works. Trying to sort by customer_name here would raise an error.
country
---------
Germany
Mexico
UK
(4 rows)
country | city
---------+--------------
Germany | Berlin
Germany | Mannheim
Mexico | Mexico City
UK | London
| Buenos Aires
(5 rows)COUNT(DISTINCT) and DISTINCT ON
When you only need "how many countries?" rather than the list, use COUNT(DISTINCT country). Aggregate functions skip NULL, so the answer here is 3, not 4: SELECT DISTINCT shows the NULL row, but COUNT(DISTINCT) does not count it.
SELECT COUNT(*) AS all_rows, -- 7
COUNT(country) AS with_country, -- 6
COUNT(DISTINCT country) AS countries -- 3
FROM customers;DISTINCT ON (column) exists only in PostgreSQL. It keeps one row per value of the column, namely the row that comes first according to ORDER BY, which makes it the shortest way to answer "each customer's latest order". The leading ORDER BY expressions must match the DISTINCT ON expressions. MySQL and SQL Server lack it; there you use a window function such as ROW_NUMBER instead.
In real projects
Where this shows up in real projects
Admin dashboards often build filter options straight from the data: SELECT DISTINCT status FROM orders ORDER BY status fills the order-status dropdown, and COUNT(DISTINCT customer_id) produces the "customers who bought this month" KPI. Counting order rows with COUNT(*) would count a customer with two orders twice, so DISTINCT is essential there.
As tables grow, running DISTINCT over millions of orders every time a dropdown opens gets slow. Teams then keep statuses in a small lookup table such as order_statuses and read from that instead. For reports like "each customer's latest login", PostgreSQL projects commonly pair DISTINCT ON with an index on (customer_id, created_at DESC), so each customer's newest row is read straight from the index.
Common mistakes
Common mistakes
1. Thinking DISTINCT applies only to the first column
SELECT DISTINCT country, customer_name returns every row, because every customer name differs. DISTINCT is not a function: even written as DISTINCT(country), customer_name it applies to the whole column list. If you want one customer per country, use DISTINCT ON (country).
2. Hiding a bad JOIN behind DISTINCT
When a query returns repeated rows, adding DISTINCT makes the output look right, but the missing join condition or misunderstood one-to-many relationship is still there. The moment you add SUM or COUNT, the multiplied rows produce wrong numbers. Find out why the rows repeat first.
3. Assuming DISTINCT output is sorted
When duplicates are removed by sorting, the output happens to look sorted, but once the planner switches to hashing the order is gone. After a few updates, rerunning DISTINCT without ORDER BY can give a jumbled order such as UK, Germany, Mexico.
Best practices
Best practices
- Pair every DISTINCT with ORDER BY, especially for lists a user will see in a dropdown or report.
- Keep only the columns that define "duplicate" in the SELECT list.
- When a query returns repeated rows, check the JOIN and WHERE before reaching for DISTINCT.
- If you only need a number, compute COUNT(DISTINCT ...) in the database instead of counting a list in the app.
Mini challenge
Mini challenge: two questions about order history
Write two queries on the orders table: first, every product that has ever been ordered (each once, alphabetically); second, each customer's most recent order with its product and time.
- The first query returns exactly three products
- The second query returns one row per customer
- In the second query, DISTINCT ON and ORDER BY must line up
CREATE TABLE orders (
order_id integer PRIMARY KEY,
customer text NOT NULL,
product text NOT NULL,
ordered_at timestamp NOT NULL
);
INSERT INTO orders VALUES
(1, 'mya', 'Keyboard', '2026-04-01 09:00'),
(2, 'kyaw', 'Mouse', '2026-04-01 11:30'),
(3, 'mya', 'Monitor', '2026-04-03 14:00'),
(4, 'hla', 'Mouse', '2026-04-02 08:15'),
(5, 'kyaw', 'Keyboard', '2026-04-05 16:45'),
(6, 'mya', 'Mouse', '2026-04-02 10:00');
-- TODO 1: each product once, A to Z
SELECT product
FROM orders;
-- TODO 2: one row per customer: their newest order
-- (customer, product, ordered_at)Expected: Query 1: Keyboard, Monitor, Mouse. Query 2: hla, Mouse (2026-04-02 08:15); kyaw, Keyboard (2026-04-05 16:45); mya, Monitor (2026-04-03 14:00).
Show hint
With DISTINCT ON (customer), ORDER BY must start with customer; follow it with ordered_at DESC so each customer's newest row comes first.
Show solution
SELECT DISTINCT product
FROM orders
ORDER BY product;
SELECT DISTINCT ON (customer) customer, product, ordered_at
FROM orders
ORDER BY customer, ordered_at DESC;Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- SELECT DISTINCT compares the combination of every selected column.
- DISTINCT collapses NULLs into one row, while COUNT(DISTINCT) does not count NULL at all.
- DISTINCT gives no order: add ORDER BY, using only columns from the SELECT list.
- DISTINCT ON is PostgreSQL's "first row per group" tool.
PostgreSQL SQL Tutorial — PostgreSQL Global Development Group