SQL Quest › SQL Interview Questions › NULL Handling
Blank Is Not NULL: A Port Data-Quality Report
Before modelling, a data team profiles missing values by embarkation port. Two kinds of missing are hiding in passengers: age is NULL for 177 passengers, and one passenger's embarked is an empty string — not NULL, just ''.
Show exactly these 5 columns, in this order:
- port — embarked, except that a NULL or blank port becomes 'Unknown'
- passengers — everyone from that port
- ages_missing — passengers from that port with no age
- avg_age_known — the average of the ages that are recorded, rounded to 1 decimal
- avg_age_filled — the average after each missing age is filled with the average age of passengers in the same pclass and the same sex, computed over the whole ship rather than per port, rounded to 1 decimal
Order by passengers descending, then port.
Three NULL rules meet in this report. COALESCE only replaces NULL — it leaves '' exactly where it was, so a blank port has to be turned into NULL first. AVG ignores NULLs, which is why avg_age_known needs no filter and why an average over each pclass and sex group is a clean fill value. And COUNT(age) counts known ages, not passengers.
The fill has to be computed before you group by port. Group first and the class-and-sex averages are gone.
Solve it in the browser editor →
Runs on SQLite in your browser, graded against the expected result, no signup. A wrong answer gets a diagnosis, not just "incorrect".
Schema
passengers
| passenger_id | survived | pclass | name | sex | age | sibsp | parch | fare | embarked |
|---|---|---|---|---|---|---|---|---|---|
| 1 | 0 | 3 | Braund, Mr. Owen Harris | male | 22 | 1 | 0 | 7.25 | S |
| 2 | 1 | 1 | Cumings, Mrs. John Bradley | female | 38 | 1 | 0 | 71.28 | C |
| 3 | 1 | 3 | Heikkinen, Miss. Laina | female | 26 | 0 | 0 | 7.93 | S |
Expected output: 4 rows — S, C, Q and a one-passenger Unknown
Hint
Concepts
SELECT NULL Handling COALESCE NULLIF Window Functions PARTITION BY CTE GROUP BY Aggregation
Practise the topic: SQL practice questions · NULL handling practice · Window function practice · CTE practice · GROUP BY exercises · Advanced SQL interview questions
Read the concept: IS NULL vs = NULL
Related questions
Where would this cost you points in an interview?
Ten questions, no signup: a Skillmap across nine SQL skills and the one to fix first.
Take the readiness test