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