COUNT

Basic SQL
≈ 1 min read

COUNT(*) counts rows

COUNT(*) returns the number of rows in a set, regardless of whether individual columns contain NULL.

SELECT COUNT(*)
FROM users;

If 42 rows remain after WHERE, COUNT(*) returns 42.

COUNT(column) counts only known values

SELECT COUNT(email)
FROM users;

This form counts only rows where email is not NULL. If there are 100 users but only 73 have an email, the result is 73.

DISTINCT can be used inside COUNT

SELECT COUNT(DISTINCT country)
FROM users;

The query counts the number of distinct known country values, not the number of users.

COUNT(*) and COUNT(column) answer different questions. The first counts rows, while the second counts non-NULL values of a specific expression. The difference is especially important when the column allows NULL.