Querydrill

Level 2: Aggregation Exercise 38 of 161 Easy NULL handling

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)

idnamedept_idsalaryhire_datemanager_id
1Ava21300002019-03-15NULL
2Ben21050002020-07-011
3Cleo1820002021-01-107
4Dan1760002022-05-237
5Eve3540002022-09-1211
6Finn2980002021-11-301
7Gia1990002018-06-04NULL
8Hugo3610002020-02-18NULL
9Iris4880002019-10-07NULL
10Jack4720002023-04-179
11KaiNULL500002024-01-088

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 exercise

More exercises in Aggregation