skipnothing/SQL

COUNT(*) vs COUNT(col)

Six rows sit in orders, two with no amount and one amount repeated. The question 'how many?' has three honest answers here, and which one you get depends on whether you're counting rows, values, or distinct values.

  • ▸Six rows in, COUNT(*) says 6, COUNT(amount) says 4: the missing two are the blank cells.
  • ▸COUNT(amount) 4, COUNT(DISTINCT amount) 3: that last gap is the one repeated value.
  • ▸Add an ELSE 0 to the CASE and the count silently returns every row again.
BUILDS ON
01

Counting rows, ignoring contents

The orders table holds six rows. Two of them never had an amount recorded, and one amount, 42.00, lands on two different rows. None of that touches the most basic question you can ask a table: how many rows are in it?

That question has a dedicated form, COUNT(*), and the * is the whole point. It is not shorthand for 'every column'. It is a signal that says count the rows themselves and look at nothing inside them. So COUNT(*) walks the table, adds one for every row it lands on, and returns 6. The two missing amounts do not lower it, because it never reads the amount column. The repeated 42.00 does not merge, because it never compares two values. Six rows on the table, six from COUNT(*), every time.

Like every form of COUNT, it cannot come back empty-handed. Run it on a table with no rows and you get 0, a real number, not the NULL that SUM or AVG hand back when there is nothing to add. The row tally always has an answer, even when the answer is none.

SIX ROWS, ONE NUMBER

Keep going, sign up to unlock the rest

3 more parts in this topic, plus 30+ more topics in SQL.

Sign up, it's freeSee the full SQL