AggregateSQL standard

COUNT

Counts rows or values that aren't NULL.

Syntax

COUNT(*)
COUNT(<column>)
COUNT(DISTINCT <column>)

COUNT(*) counts all rows. COUNT(<column>) — only those where the column isn't NULL. COUNT(DISTINCT <column>) — how many different values there are. Together with GROUP BY it counts separately for each group.

Data for the examples

employees

namedepartmentsalarybonusphone
Emmabackend1200300+44 7700 900123
Liambackend1000NULLNULL
Oliviafrontend1350150+44 7700 900456
Noahfrontend950NULL+44 7700 900789
Sophiadesign1200200NULL

These tables already exist in the sandbox — the examples below use them. Want to try this in your own database? Copy the SQL.

How many employees in total
SELECT COUNT(*) AS total
FROM employees;
total
5
Three different counts
SELECT COUNT(*) AS all_rows,
COUNT(bonus) AS with_bonus,
COUNT(DISTINCT department) AS departments
FROM employees;
all_rowswith_bonusdepartments
533

Two employees have no bonus, so COUNT(bonus) gives 3, not 5.

How many people in each department
SELECT department, COUNT(*) AS people
FROM employees
GROUP BY department
ORDER BY department;
departmentpeople
backend2
design1
frontend2

Watch out

COUNT(<column>) silently skips NULL. If you want the number of rows, write COUNT(*).

If there are no rows, COUNT gives 0, while SUM gives NULL. So there's no need to wrap COUNT in COALESCE.

With a LEFT JOIN, COUNT(*) counts 1 even where no match was found. To get 0, count a column from the right-hand table: COUNT(o.id).

Related functions