Conditional counts (COUNT IF)
SUM 0/1 flags per condition instead of one query per condition.
The task
You want, per customer, how many orders are pending and how many shipped, in one query instead of two.
The snippet
Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.
SELECT customer_id,
SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) AS pending_orders,
SUM(CASE WHEN status = 'shipped' THEN 1 ELSE 0 END) AS shipped_orders,
COUNT(*) AS all_orders
FROM orders
GROUP BY customer_id
ORDER BY customer_id;
Как это работает
The CASE emits 1 for matching rows and 0 otherwise, and the grouped SUM adds the 1s up: a conditional count in one pass. COUNT(CASE WHEN status = 'pending' THEN 1 END) works too, because COUNT skips NULLs. Engines with a FILTER clause (PostgreSQL, SQLite 3.30+) express it directly as COUNT(*) FILTER (WHERE ...).
Variations
FILTER clause (PostgreSQL, SQLite)
PostgreSQL SQLiteSELECT customer_id,
COUNT(*) FILTER (WHERE status = 'pending') AS pending_orders,
COUNT(*) FILTER (WHERE status = 'shipped') AS shipped_orders
FROM orders
GROUP BY customer_id;
Questions that come up
What happens if I forget the ELSE 0?
The CASE yields NULL for non-matching rows and SUM ignores NULLs, so the count is still right, except that a customer with no matching rows gets NULL instead of 0. With AVG the ELSE matters more: ELSE 0 averages over every row, while no ELSE averages over the matching rows only.
Keep reading
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.