Part 04 / Topic 2 of 6
Three kinds of count
These look interchangeable. They answer three different questions:
SELECT count(*) AS all_rows,
count(city) AS rows_with_city,
count(DISTINCT city) AS distinct_cities
FROM customers;
all_rows | rows_with_city | distinct_cities
----------+----------------+-----------------
6 | 5 | 4
(1 row)
count(*)— how many rows? (6 customers — the only aggregate that ignores NULLs entirely, because it never looks at a value.)count(city)— how many rows have a non-NULL city? (5 — Sara's NULL is skipped, like every aggregate skips NULLs.)count(DISTINCT city)— how many different cities? (4 — two customers share Pune, and NULL isn't counted.)
Interviewers love this trio precisely because the differences only show up when NULLs and duplicates exist — which, in real data, is always.
🧪 Quick quiz — answer from memory, then check.
- shopdb's customers: 6 rows, one NULL city, two Pune. Give all three counts.
- Which count would you use for "how many customers have an email on file"?
Show the answers
count(*)= 6,count(city)= 5,count(DISTINCT city)= 4.count(email)— rows where email is not NULL.
Done here? The practice set for Part 4 — 7 exercises with solutions — is on the part page.