SQL how-to
How to count rows that match a condition in SQL
Updated · Tested on PostgreSQL 18.6 and SQLite 3.54.1 (results generated , re-checked on every release)
Short answer
Put the condition inside the aggregate: COUNT(*) FILTER (WHERE adopted), SUM(CASE WHEN adopted THEN 1 ELSE 0 END) or COUNT(CASE WHEN adopted THEN 1 END). Unlike WHERE, it lets one query count several conditions at once.
The task: Count how many rows meet a condition, several conditions side by side in one query.
Several counts in one row
SELECT COUNT(*) AS pets,
COUNT(*) FILTER (WHERE adopted) AS adopted,
COUNT(*) FILTER (WHERE NOT adopted AND age >= 8) AS waiting_seniors,
COUNT(*) FILTER (WHERE breed IS NULL) AS unknown_breed
FROM pets;Result (PostgreSQL and SQLite, identical): 1 row
| pets | adopted | waiting_seniors | unknown_breed |
|---|---|---|---|
| 20 | 8 | 4 | 6 |
Try it: PostgreSQL playground · SQLite playground
How it works
- 1
COUNT(*) FILTER (WHERE adopted)Counts only the rows where the condition is true.
- 2
COUNT(*) AS petsThe plain total, in the same row, for comparison.
More examples
Per group, with the share
The CASE form, plus the adopted share per species.
SELECT species,
COUNT(*) AS pets,
SUM(CASE WHEN adopted THEN 1 ELSE 0 END) AS adopted,
ROUND(100.0 * SUM(CASE WHEN adopted THEN 1 ELSE 0 END) / COUNT(*), 0) AS adopted_pct
FROM pets
GROUP BY species
ORDER BY species;Result (PostgreSQL and SQLite, identical): 4 rows
| species | pets | adopted | adopted_pct |
|---|---|---|---|
| bird | 2 | 1 | 50 |
| cat | 7 | 3 | 43 |
| dog | 8 | 2 | 25 |
| rabbit | 3 | 2 | 67 |
Try it: PostgreSQL playground · SQLite playground
COUNT(CASE …) without ELSE
COUNT skips NULLs, and a CASE with no ELSE gives NULL for the other rows.
SELECT COUNT(CASE WHEN status = 'delivered' THEN 1 END) AS delivered,
COUNT(CASE WHEN status = 'cancelled' THEN 1 END) AS cancelled,
COUNT(*) AS all_orders
FROM orders;Result (PostgreSQL and SQLite, identical): 1 row
| delivered | cancelled | all_orders |
|---|---|---|
| 13 | 2 | 17 |
Try it: PostgreSQL playground · SQLite playground
Variations
Why not WHERE?
WHERE adopted would drop every other row, so you could count only one condition per query. Inside the aggregate, each count has its own condition.
Common mistakes
COUNT(CASE WHEN … THEN 1 ELSE 0 END): 0 isn't NULL, so it counts every row. Drop the ELSE, or use SUM.Dividing two counts as whole numbers: multiply by 100.0 first.
Conditions that miss NULLs:
WHERE breed <> 'Beagle'doesn't count rows where breed is NULL.
PostgreSQL and SQLite
All three forms work in both (FILTER in SQLite since 3.30). SQLite stores true as 1, so SUM(adopted) also works there, but not in PostgreSQL, where a boolean can't be summed.
Official documentation
Go deeper
- Guide: SQL CASE WHEN
- Lesson: Count, sum, average (Pro)
Make it stick in five minutes a day
“Count, sum, average” teaches this step by step on a real database, with instant feedback. Part of sqlstreak Pro; the first lessons are free.