// conditional reference

SQL SUM(CASE WHEN) pattern

One query, several conditional totals: CASE inside an aggregate, portable everywhere.

類別
條件
Returns
numeric
In this category
28 of 43

語法

SUM(CASE WHEN c THEN 1 ELSE 0 END) | COUNT(CASE WHEN c THEN 1 END)

引擎支援

引擎Support備註
SQL Server 是 Supported under this name.
PostgreSQL 是 Supported under this name.
MySQL 是 Supported under this name.
SQLite 是 Supported under this name.
Oracle 是 Supported under this name.

範例

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;

小知識

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

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// fewer lookups

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.