Video in progress

What does `SELECT DISTINCT` do, and how is it different from GROUP BY?

DISTINCT collapses completely identical rows in the result into one. GROUP BY also groups, but lets you compute an aggregate (count, sum) for each group. Written without an aggregate, the two often give the same result and the same plan.

📖 Answer

SELECT DISTINCT city FROM users;
SELECT city FROM users GROUP BY city;   -- same result

SELECT city, count(*) FROM users GROUP BY city;  -- you can't do this with DISTINCT

DISTINCT applies to the combination of all selected columns: with SELECT DISTINCT city, name, the same city appears many times.

There is a bad habit in practice: the JOIN produces duplicates, so you "fix" it by putting DISTINCT at the end of the query. That hides the effect, not the cause, and it's expensive on a big result because the database has to sort or hash every row. Often the right fix is EXISTS or a more precise JOIN condition.

PostgreSQL has a useful extension, DISTINCT ON: one row from each group, for example each user's most recent order:

SELECT DISTINCT ON (user_id) user_id, id, created_at
FROM orders
ORDER BY user_id, created_at DESC;