DISTINCT & the Order of Execution
DISTINCT – remove duplicate rows
SELECT DISTINCT city FROM users– each city once- With several columns, the combination must be unique:
SELECT DISTINCT user_id, category_id - NULLs are treated as equal for DISTINCT (only one NULL row)
count(DISTINCT col)– count unique values- ⚠️ DISTINCT can hide bugs (like accidental duplicate rows from a bad join). Fix the cause instead of adding DISTINCT everywhere.
DISTINCT ON (PostgreSQL) ⭐
Keep one row per group — the first one according to ORDER BY:
SELECT DISTINCT ON (user_id) user_id, title, amount
FROM expenses
ORDER BY user_id, amount DESC; -- each user's biggest expense
The ORDER BY must start with the DISTINCT ON columns.
The logical order of execution ⭐
You write SQL in this order:
SELECT → FROM → WHERE → GROUP BY → HAVING → ORDER BY → LIMIT
But the database logically runs it in this order:
- FROM / JOIN – gather the rows
- WHERE – filter rows
- GROUP BY – form groups
- HAVING – filter groups
- SELECT – compute columns and aliases (window functions run here)
- DISTINCT – remove duplicates
- ORDER BY – sort (aliases are available now ✅)
- LIMIT / OFFSET – cut the result
This explains…
- WHERE can't use SELECT aliases (SELECT hasn't happened yet)
- WHERE can't use aggregates like
sum()→ use HAVING - ORDER BY can use aliases
- LIMIT applies last, after sorting
Example
-- Unique values
SELECT DISTINCT city FROM users ORDER BY city;
-- Kathmandu, Lalitpur, Pokhara, NULL
-- Distinct combinations
SELECT DISTINCT user_id, category_id FROM expenses WHERE user_id = 2 ORDER BY 2;
-- Count unique values
SELECT count(DISTINCT city) AS cities FROM users; -- 3 (NULL not counted)
SELECT count(DISTINCT user_id) AS users_with_expenses FROM expenses; -- 4
-- DISTINCT ON: each user's single biggest expense
SELECT DISTINCT ON (user_id) user_id, title, amount
FROM expenses
ORDER BY user_id, amount DESC;
-- 1 | Running shoes | 6500.00
-- 2 | Paragliding | 8500.00
-- 3 | Flight to Pokhara | 7800.00
-- 4 | Concert | 2500.00
-- DISTINCT ON: each user's most recent expense
SELECT DISTINCT ON (user_id) user_id, title, spent_on
FROM expenses
ORDER BY user_id, spent_on DESC;
-- Order of execution in action:
SELECT category_id, sum(amount) AS total -- 5. SELECT
FROM expenses -- 1. FROM
WHERE spent_on >= '2026-10-01' -- 2. WHERE (row filter)
GROUP BY category_id -- 3. GROUP BY
HAVING sum(amount) > 5000 -- 4. HAVING (group filter)
ORDER BY total DESC -- 7. ORDER BY (alias OK!)
LIMIT 3; -- 8. LIMIT