QA Interview Hub · Knowledge base · Quizzes · Українська

SQL › Aggregation

How do COUNT(*), COUNT(col) and COUNT(DISTINCT col) differ?

COUNT(*) counts all rows, COUNT(col) only the rows where col is not NULL, and COUNT(DISTINCT col) the number of different non-NULL values. So COUNT(*) - COUNT(col) equals the number of NULLs in the column. After a LEFT JOIN, a column of the right table is counted instead of COUNT(*), so that a missing pair gives 0 and not 1.

SQL · Aggregates

After a migration users has 100 rows but COUNT(phone) returns 70. A defect or normal?

After a migration a tester compares counts: users has 100 users but COUNT(phone) returns 70. Were 30 phone numbers lost, or were they empty before the migration too? The three forms of COUNT give different numbers on the same data, and telling them apart is a basic data-checking skill.

How it works and why. COUNT(*) counts rows and looks at no column, so NULL does not affect it. COUNT(col) evaluates the expression for each row and counts those where the result is not NULL. COUNT(DISTINCT col) first drops repeats among the non-NULL values and then counts. COUNT(1) and COUNT(*) are the same: a constant is never NULL. A rule follows: COUNT(*) - COUNT(col) equals the number of NULLs in the column, and COUNT(col) - COUNT(DISTINCT col) the number of "extra" repeats.

Three COUNTs on the same data

users
idnamephone
1Anna0501
2IvanNULL not counted
3Olha0502
4PetroNULL not counted
5Sasha0501
result
expressionvalue
COUNT(*)5
COUNT(phone)3
COUNT(DISTINCT phone)2
COUNT(*) - COUNT(phone)2
Figure 1. Two empty phones drop out of COUNT(phone), and two equal values 0501 merge into one.

Example: what 100 and 70 mean. A query that answers the migration question at once:

SELECT COUNT(*)                AS users_total,
       COUNT(phone)            AS with_phone,
       COUNT(DISTINCT phone)   AS distinct_phones,
       COUNT(*) - COUNT(phone) AS without_phone
FROM users;
-- on the Figure 1 data: 5 | 3 | 2 | 2

The without_phone difference shows how many fields are empty. Then it has to be compared with the source: if the old system also had an empty phone for 30 users, that is normal, and if not, data was lost during the migration. The number decides nothing by itself, it only points where to look.

COUNT after a LEFT JOIN

wrong

COUNT(*)

A user with no orders gets 1: the LEFT JOIN result has a row for them with NULL in the order columns, and COUNT(*) counts rows.

right

COUNT(o.id)

The same user gets 0: o.id in their row is NULL and COUNT(column) skips it.

Figure 2. After a LEFT JOIN count a column of the right table, otherwise "no orders" turns into "one order".
-- orders per user, including users with none
SELECT u.name, COUNT(o.id) AS orders_cnt
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
GROUP BY u.id, u.name;

Limits and alternatives. COUNT(DISTINCT col) does not count NULL as a separate value, so empty values drop out of the unique ones. It is more expensive than a plain COUNT because the database has to remove repeats, which is noticeable on large tables. Uniqueness often depends on how the data is normalised:

-- how many different addresses if case does not matter
SELECT COUNT(DISTINCT email)        AS raw_cnt,
       COUNT(DISTINCT lower(email)) AS normalized_cnt
FROM users;
-- the numbers differ: some addresses differ only in case

PostgreSQL does not support COUNT(DISTINCT a, b) with two columns (MySQL does), so pairs are counted through a subquery:

-- PostgreSQL does not accept COUNT(DISTINCT a, b); wrap a subquery
SELECT COUNT(*)
FROM (SELECT DISTINCT user_id, status FROM transactions) AS pairs;

Two more practical details. In PostgreSQL COUNT(*) over a whole large table reads it completely, because every transaction snapshot sees its own rows, so on millions of rows such a query is slow. If you only need to know whether at least one row exists, EXISTS is cheaper. And COUNT returns bigint: in the JavaScript pg driver it arrives as the string "5" by default, so a comparison with the number 5 in a test fails without a type conversion.

Common mistakes.

  • COUNT(*) after LEFT JOIN instead of COUNT(a column of the right table): "zero orders" becomes "one".
  • Expecting COUNT(col) to count all rows: a NULL in the column silently reduces the result.
  • Assuming COUNT(DISTINCT col) counts NULL as one unique value: it skips it.
  • Counting unique emails without lower() and missing duplicates that differ in case.
  • Comparing COUNT with an expected number in a test without checking types: the string "5" does not equal the number 5.

Check yourself

users has 100 rows, COUNT(phone) returns 70 and COUNT(DISTINCT phone) returns 65. What do these numbers say?

Answer

30 users have an empty phone (100 - 70). Among the 70 filled ones there are 5 repeats: the same number appears for more than one user. That may be normal (a shared number) or a defect, so it is compared with the domain rules.

A column holds the values 'a', 'a' and NULL. What do COUNT(*), COUNT(col) and COUNT(DISTINCT col) return?

Answer

3, 2 and 1. COUNT(*) counts all three rows, COUNT(col) skips the NULL, and COUNT(DISTINCT col) then merges the two 'a' into one.

A user has no orders. Which COUNT gives 0 after a LEFT JOIN: COUNT(*) or COUNT(o.id)?

Answer

COUNT(o.id). For such a user the LEFT JOIN returns one row with NULL in o.id: COUNT(*) counts that row and gives 1, while COUNT(o.id) skips the NULL and gives 0.

In an interview. Junior: COUNT star counts all rows, COUNT of a column only those where the value is not NULL, and COUNT DISTINCT the number of unique non-NULL values. The difference between the first two shows how many fields are empty, and I use it to check data completeness after a migration. Middle/Senior: After a LEFT JOIN I count a column of the right table, otherwise a missing link gives 1 instead of 0. COUNT(DISTINCT) ignores NULL and is more expensive, and in PostgreSQL several columns need a subquery. I check types too: a bigint can arrive as a string in the driver.

More articles in this chapter