Full answer
sql
CREATE TABLE departments (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
dept_id INTEGER REFERENCES departments(id),
manager_id INTEGER REFERENCES employees(id),
salary INTEGER,
hire_date TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
(1,'Asha', 1,NULL,120000,'2019-03-01'),
(2,'Ravi', 1,1, 95000,'2020-07-15'),
(3,'Mei', 1,1, 95000,'2021-01-10'),
(4,'Tom', 2,1, 70000,'2022-05-20'),
(5,'Sara', 2,4, 62000,'2023-02-01'),
(6,'Diego',3,1, 55000,'2021-11-30'),
(7,'Lena', NULL,4, NULL, '2024-06-03'),
(8,'Omar', 3,6, 48000,'2024-09-09');sql
SELECT dept_id, COUNT(*) AS n FROM employees WHERE salary > 60000 GROUP BY dept_id ORDER BY dept_id;| dept_id | n |
|---|---|
| 1 | 3 |
| 2 | 2 |
Support (dept 3) pays 55000 and 48000, so it vanishes from the result. Conditional counting keeps every department that has employees:
sql
SELECT dept_id, COUNT(CASE WHEN salary > 60000 THEN 1 END) AS n FROM employees WHERE dept_id IS NOT NULL GROUP BY dept_id ORDER BY dept_id;| dept_id | n |
|---|---|
| 1 | 3 |
| 2 | 2 |
| 3 | 0 |
Legal still does not appear, because it has no employees at all. Starting from departments with a LEFT JOIN is the way to include it.
sql
CREATE TABLE departments (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
dept_id INTEGER REFERENCES departments(id),
manager_id INTEGER REFERENCES employees(id),
salary INTEGER,
hire_date TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
(1,'Asha', 1,NULL,120000,'2019-03-01'),
(2,'Ravi', 1,1, 95000,'2020-07-15'),
(3,'Mei', 1,1, 95000,'2021-01-10'),
(4,'Tom', 2,1, 70000,'2022-05-20'),
(5,'Sara', 2,4, 62000,'2023-02-01'),
(6,'Diego',3,1, 55000,'2021-11-30'),
(7,'Lena', NULL,4, NULL, '2024-06-03'),
(8,'Omar', 3,6, 48000,'2024-09-09');
SELECT dept_id, COUNT(*) AS n FROM employees WHERE salary > 60000 GROUP BY dept_id ORDER BY dept_id;
SELECT dept_id, COUNT(CASE WHEN salary > 60000 THEN 1 END) AS n FROM employees WHERE dept_id IS NOT NULL GROUP BY dept_id ORDER BY dept_id;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- WHERE filters before grouping
- Groups with no qualifying rows disappear
- Conditional COUNT keeps every group
- Start from the parent table to include empty parents
Common mistakes
- Expecting zero-count rows from a WHERE-filtered GROUP BY
- Moving the condition to HAVING and changing the meaning
Follow-ups
- How would you include Legal?
- When is HAVING the right place?
Tips
- Show the conditional-count version