SQL COUNT
COUNT() returns the number of rows that match a query. It comes in three flavours:
| Form | Counts |
|---|---|
COUNT(*) |
all rows |
COUNT(column) |
rows where column is not NULL |
COUNT(DISTINCT column) |
different non-NULL values |
Counting rows
SELECT COUNT(*) AS products FROM products;
SELECT COUNT(*) AS out_of_stock FROM products WHERE stock = 0;products
--------
30
(1 row)
out_of_stock
------------
2
(1 row)
COUNT(column) skips NULLs
SELECT COUNT(*) AS orders,
COUNT(shipped_date) AS with_shipped_date,
COUNT(DISTINCT customer_id) AS different_customers,
COUNT(DISTINCT employee_id) AS different_employees
FROM orders;orders | with_shipped_date | different_customers | different_employees
-------+-------------------+---------------------+--------------------
40 | 25 | 18 | 4
(1 row)
Counting per group
COUNT is most useful with GROUP BY. How many orders does each status have?
SELECT status, COUNT(*) AS orders
FROM orders
GROUP BY status
ORDER BY orders DESC;status | orders
-----------+-------
delivered | 16
shipped | 9
processing | 8
cancelled | 7
(4 rows)
How many orders did each employee handle? We join to employees to show the names:
SELECT e.first_name, e.last_name, COUNT(o.order_id) AS orders
FROM employees AS e
JOIN orders AS o ON o.employee_id = e.employee_id
GROUP BY e.employee_id
ORDER BY orders DESC, e.employee_id;first_name | last_name | orders
-----------+-----------+-------
Aisha | Bello | 16
Rosa | Delgado | 11
Owen | Price | 7
Tom | Becker | 6
(4 rows)
Only four employees appear — all sales reps: the others never took an order. (A LEFT JOIN would show them with 0 — see the joins lessons.)
Counting with a condition
To count several things at once, put a condition inside SUM or COUNT with CASE. In SQLite a comparison is 1 or 0, so SUM(condition) counts the true rows:
SELECT COUNT(*) AS customers,
SUM(email IS NULL) AS missing_email,
COUNT(CASE WHEN country = 'USA' THEN 1 END) AS in_usa
FROM customers;customers | missing_email | in_usa
----------+---------------+-------
25 | 4 | 2
(1 row)
COUNT(CASE WHEN … THEN 1 END) is portable; SUM(condition) works in SQLite and MySQL. PostgreSQL also offers COUNT(*) FILTER (WHERE condition), which SQLite supports too.
Tip:
COUNT(*)is not slower thanCOUNT(1)orCOUNT(id)— the database knows*simply means "rows". UseCOUNT(*)unless you deliberately want to skip NULLs.
Test yourself
If 4 of 25 customers have a NULL email, what is COUNT(email)?
- 25
- 4
- 21
- NULL
What does COUNT(DISTINCT country) count?
- All rows
- Rows with a country
- Different country values
- Countries with more than one customer
Which is a portable way to count only rows where status = 'shipped' in one query with other counts?
- COUNT(status = 'shipped')
- COUNT(CASE WHEN status = 'shipped' THEN 1 END)
- COUNT(*) WHERE status = 'shipped'
- COUNTIF(status, 'shipped')