Cheatsheet Pages / SQL Cheatsheet

How to count with conditions in SQL — CASE WHEN inside aggregates

You want several differently-defined metrics — total staff and high earners — from one pass over the table.

Every example runs against the cheatsheet's sample tables — departments(id, name), employees(id, name, dept_id, salary, manager_id, hired_on) and orders(id, emp_id, amount, ordered_on) — and was executed and verified against SQLite, so you can paste it in and get the same result.

SELECT COUNT(*) AS total,
       SUM(CASE WHEN salary >= 90000 THEN 1 ELSE 0 END) AS high_earners
FROM employees;
-- total 7 / high earners 2 (Alice, Bob). Several metrics with different rules in one pass
SQL Cheatsheet one-page card — queries that actually work
The full one-page card — SQL Cheatsheet. Get the complete cheatsheet on GitHub