SQL SUM(CASE WHEN) pattern
One query, several conditional totals: CASE inside an aggregate, portable everywhere.
- Category
- Conditional
- Returns
numeric- In this category
- 28 of 43
Syntax
SUM(CASE WHEN c THEN 1 ELSE 0 END) | COUNT(CASE WHEN c THEN 1 END)
Engine support
| Engine | Support | Notes |
|---|---|---|
| SQL Server | Yes | Supported under this name. |
| PostgreSQL | Yes | Supported under this name. |
| MySQL | Yes | Supported under this name. |
| SQLite | Yes | Supported under this name. |
| Oracle | Yes | Supported under this name. |
Examples
Any engine
SELECT dept, SUM(CASE WHEN paid = 1 THEN amount ELSE 0 END) AS paid_amt FROM invoices GROUP BY dept;
PostgreSQL
SELECT dept, COUNT(*) FILTER (WHERE paid) AS paid_count FROM invoices GROUP BY dept;
Good to know
- Without ELSE, CASE yields NULL and aggregates skip it: that is why SUM needs ELSE 0 but COUNT(CASE WHEN c THEN 1 END) works bare.
- MySQL and SQLite accept bare SUM(paid = 1) because comparisons return 1 or 0; PostgreSQL needs SUM((paid = 1)::int) or COUNT(*) FILTER (WHERE ...).
- The pattern is the standard pivot: one CASE per output column, grouped by the row key.
- Write the condition for the column's real type: WHEN paid THEN on a PostgreSQL or Oracle 23ai BOOLEAN, WHEN paid = 1 THEN on SQL Server BIT and MySQL or SQLite 0/1 integers.
Questions about SUM(CASE)
Why ELSE 0 in SUM but not in COUNT?
COUNT(CASE WHEN c THEN 1 END) counts only the matching rows, so NULLs dropping out is exactly right; bare SUM(CASE WHEN c THEN 1 END) returns NULL for a group with no matches, while ELSE 0 gives a clean 0.
Is there a shorter form?
PostgreSQL and SQLite: COUNT(*) FILTER (WHERE cond). MySQL and SQLite: SUM(cond), since a comparison is 1 or 0.
How do I pivot rows to columns?
One conditional aggregate per output column, all sharing the GROUP BY key.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.