Functions, Dates and Cleaning · Problem 23 of 118

Unknown Guardian

MediumFunctions, Dates and CleaningSchool data

Return student_id and guardian for students 1 to 15, where guardian is the guardian_name, or the text 'unknown' when it is missing. Sort by student_id.

Hint 1

COALESCE(a, b) returns a unless it is NULL, otherwise b.

Reference solution

SELECT student_id,
       COALESCE(guardian_name, 'unknown') AS guardian
FROM students
WHERE student_id BETWEEN 1 AND 15
ORDER BY student_id;

COALESCE(x, y, z, ...) returns the first value that is not NULL. It is the standard way to provide a default for missing data, in reports and in calculations (COALESCE(discount, 0)). Be careful to choose a default that is honest: showing 0 for an unknown number can hide the fact that the value is missing.

Another way. COALESCE is a short form of this CASE expression.

SELECT student_id,
       CASE WHEN guardian_name IS NULL THEN 'unknown' ELSE guardian_name END AS guardian
FROM students
WHERE student_id BETWEEN 1 AND 15
ORDER BY student_id;