Q&A-12Explain COUNT(*), COUNT(column), and COUNT(DISTINCT column) with a case where choosing wrongly matters.
Answer
The 60-second answer. COUNT(*) counts rows. COUNT(col) counts rows where col IS NOT NULL. COUNT(DISTINCT col) counts distinct non-NULL values of col. They diverge in two places: outer joins, and joins that fan out.
The case that bites is "how many orders has each customer placed?":
SELECT c.id, COUNT(*) AS n_star, COUNT(o.id) AS n_col
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id;For a customer with no orders, the LEFT JOIN emits exactly one row with every o.* column NULL. COUNT(*) counts that row, so it returns 1. COUNT(o.id) skips it and returns 0. COUNT(*) therefore reports that every customer has at least one order: no error, no warning, just a plausible-looking report claiming all 2,000,000 customers ordered.
| customer | joined rows | COUNT(*) | COUNT(o.id) |
|---|---|---|---|
| c1, 3 orders | 3 | 3 | 3 |
| c2, 0 orders | 1 NULL-extended | 1 | 0 |
Fan-out. The distinct form matters when the join multiplies rows:
SELECT COUNT(c.id) AS wrong, COUNT(DISTINCT c.id) AS right
FROM customers c JOIN orders o ON o.customer_id = c.id
WHERE o.created_at >= '2024-06-01';If 300,000 customers placed 1,200,000 orders in June, wrong is 1,200,000 and right is 300,000. The tell is a customer count larger than the customer table: obvious if you know the magnitude, invisible otherwise.
Why COUNT(DISTINCT) costs. COUNT(*) and COUNT(col) use an incremental transition: one counter per group. COUNT(DISTINCT col) has to remember every value it has seen, so it becomes a sort or hash aggregate over the group's values. In PostgreSQL 13+ a hash aggregate that outgrows work_mem (default 4 MB) spills to disk; before 13 it simply used more memory than work_mem. Arithmetic: COUNT(DISTINCT order_id) over 50M rows holds ~50M entries; at roughly 32 bytes per hash-table entry that is ~1.6 GB against a 4 MB default. That is a spill, not a counter. (Estimate, not a benchmark.)
Approximations. BigQuery, Snowflake and Spark SQL all ship APPROX_COUNT_DISTINCT (HyperLogLog); Snowflake documents a maximum relative error of 1.6%. PostgreSQL has no built-in equivalent: you need an extension. Reach for it when the number is a dashboard figure, not when it is a billing total. Otherwise pre-aggregate so the distinct count runs over fewer rows, or maintain a summary table.
Free probe. On a base table, COUNT(*) - COUNT(col) is exactly the NULL count of col.
Engine notes. MyISAM keeps an exact row count, so COUNT(*) is O(1); InnoDB does not and scans the smallest index. PostgreSQL has no stored count either: COUNT(*) can use an index-only scan on the smallest index, but COUNT(col) needs col in that index.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.