# How to count rows that match a condition in SQL

Source: https://sqlstreak.com/sql/how-to/conditional-count · Tested on PostgreSQL 18.6 and SQLite 3.54.1; results generated 2026-11-22.


**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

```sql
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 (both engines):

| pets | adopted | waiting_seniors | unknown_breed |
| --- | --- | --- | --- |
| 20 | 8 | 4 | 6 |

### Per group, with the share

The CASE form, plus the adopted share per species.

```sql
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 (both engines):

| species | pets | adopted | adopted_pct |
| --- | --- | --- | --- |
| bird | 2 | 1 | 50 |
| cat | 7 | 3 | 43 |
| dog | 8 | 2 | 25 |
| rabbit | 3 | 2 | 67 |

### COUNT(CASE …) without ELSE

COUNT skips NULLs, and a CASE with no ELSE gives NULL for the other rows.

```sql
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 (both engines):

| delivered | cancelled | all_orders |
| --- | --- | --- |
| 13 | 2 | 17 |

## How it works

- `COUNT(*) FILTER (WHERE adopted)`: Counts only the rows where the condition is true.
- `COUNT(*) AS pets`: The plain total, in the same row, for comparison.

## 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.
