Video in progress
How do COUNT(*), COUNT(column) and COUNT(DISTINCT column) differ?
COUNT(*) counts all rows, COUNT(column) counts only the rows where that column is not NULL, and COUNT(DISTINCT column) gives the number of distinct non-NULL values.
📖 Answer
Say the table has 5 orders: two have an empty (NULL) promo_code, and the rest have 'NOV10', 'NOV10', 'VIP'.
SELECT count(*), -- 5
count(promo_code), -- 3
count(DISTINCT promo_code) -- 2
FROM orders;
This difference matters when you work with LEFT JOIN:
SELECT u.id, count(o.id) AS orders_cnt
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
GROUP BY u.id;
If you wrote count(*) here, a user with no orders would show up as 1, because the LEFT JOIN returns one row for them (with NULLs on the right side). count(o.id) correctly gives 0.
The claim that "COUNT(1) is faster than COUNT(*)" is a myth in PostgreSQL. There's no difference, and * is even optimized slightly better.
Sign up to mark studied questions and save your progress.