Skip to the workspace
Pebellslearn by building
Aggregate Queries  ›  Lesson

COUNT — How Many?

COUNT 12 minCOUNT(*) counts rows, COUNT(column) counts non-NULL values and COUNT(DISTINCT column) counts different values, returning 0 when nothing matches.

sql / COUNT — How Many?

Explore each scene at your own pace.

01 · The rule

The rule

COUNT — How Many?

COUNT(*) counts rows, COUNT(column) counts non-NULL values and COUNT(DISTINCT column) counts different values, returning 0 when nothing matches.

Compare counting rows, non-NULL values and distinct values on the same data.

"How many customers do we have?" "How many orders shipped this week?" "How many customers never gave us an email?" Counting is the first question almost every report asks. SQL answers all three with COUNT — but in three slightly different forms, and mixing them up gives believable wrong numbers.

The rule

COUNT(*) counts rows; COUNT(column) counts values that are not NULL.

COUNT is an aggregate function: it takes many rows in and gives one number out. Our customers table:

customer_id name city email
1 Asha Pune asha@example.com
2 Ravi Delhi NULL
3 Meera Pune meera@example.com
4 Kabir Mumbai kabir@example.com
SELECT COUNT(*)             FROM customers;  -- 4: every row
SELECT COUNT(email)         FROM customers;  -- 3: Ravi's NULL is skipped
SELECT COUNT(DISTINCT city) FROM customers;  -- 3: Pune, Delhi, Mumbai
  • COUNT(*) counts rows, whatever they contain.
  • COUNT(column) counts rows where that column is not NULL.
  • COUNT(DISTINCT column) counts the different non-NULL values.

WHERE runs before COUNT, so it narrows the rows first: SELECT COUNT(*) FROM customers WHERE city = 'Pune'; gives 2. And when no rows match at all, COUNT returns 0, not NULL — it is the one aggregate that always gives a number.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.