Count the missing values
An SQL exercise from Querydrill. Solve it with a SQL editor in your browser, checked on the rows it returns and again on changed data, and it is checked the moment you submit.
Try it yourself
Return two numbers in one row: the total number of employees, and how many of them have no department.
employees (11 rows)
| id | name | dept_id | salary | hire_date | manager_id |
|---|---|---|---|---|---|
| 1 | Ava | 2 | 130000 | 2019-03-15 | NULL |
| 2 | Ben | 2 | 105000 | 2020-07-01 | 1 |
| 3 | Cleo | 1 | 82000 | 2021-01-10 | 7 |
| 4 | Dan | 1 | 76000 | 2022-05-23 | 7 |
| 5 | Eve | 3 | 54000 | 2022-09-12 | 11 |
| 6 | Finn | 2 | 98000 | 2021-11-30 | 1 |
| 7 | Gia | 1 | 99000 | 2018-06-04 | NULL |
| 8 | Hugo | 3 | 61000 | 2020-02-18 | NULL |
| 9 | Iris | 4 | 88000 | 2019-10-07 | NULL |
| 10 | Jack | 4 | 72000 | 2023-04-17 | 9 |
| 11 | Kai | NULL | 50000 | 2024-01-08 | 8 |
Free, no account needed. PostgreSQL runs in your browser and your answer is checked again on changed data.
What this exercise teaches
Every aggregate except COUNT(*) skips NULLs. That is what makes COUNT(column) a quick missing-value check, and it is also why AVG(column) ignores the rows you may have wanted to count as zero.
A hint if you get stuck
COUNT(*) counts rows, COUNT(dept_id) counts only rows where dept_id is not NULL. The difference is the number of missing values. SUM(CASE WHEN dept_id IS NULL THEN 1 ELSE 0 END) works too.
Background you need
Common mistakes on this exercise
- Second number counts employees that do have a department.
- First number leaves out employees without a department.
Each of these returns a result that looks plausible. The checker catches them because it runs your query on changed data as well.
Keep going on the practice page
Your first 8 exercises on Querydrill are free, with no account. The practice page has the full editor, timed mode and all the exercises in order. A free account shows 3 reference solutions a day; Pro unlocks every exercise, every solution, timed mode and the certificate.
Open this exerciseMore exercises in Aggregation
- Customers per country
- Spend per customer
- Repeat buyers
- Customers over a spending threshold
- Revenue by month
- Average salary per department
- First and last order
- Orders per status
- Products per category
- Units sold per product
- Customers who ordered
- Average paid order
- Hires per year
- Active in several months
- Paid and refunded per customer
- Share of paid orders
- Salary bands
- Paid revenue per quarter
- Several counts in one pass (FILTER)
- Paid revenue per week (date_trunc)
- Orders per weekday (EXTRACT)
- Subtotals and a grand total (ROLLUP)
- Average lines per order (whole-number division)