Cheatsheet Pages / SQL Cheatsheet

How to compute per-group statistics in SQL — GROUP BY

Totals for the whole table are not enough — you need the numbers per department.

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 dept_id, COUNT(*) AS n, AVG(salary) AS avg_salary FROM employees GROUP BY dept_id;
-- dept 1: 3 people, avg 101000; dept 2: 2, 70000; dept 3: 1, 54000; NULL group: 1, 60000
SQL Cheatsheet one-page card — queries that actually work
The full one-page card — SQL Cheatsheet. Get the complete cheatsheet on GitHub