SQL QuestSQL Interview Questions › NULL Handling

Handle NULL Ages

MediumFreeQuerying BasicsNULL HandlingAggregation & GroupingSubqueries & CTEs

Many passengers have missing ages. Write a SQL query to show the average age by class, but replace NULL ages with the overall average age before calculating. Return pclass, avg_age_raw (with NULLs), and avg_age_filled (NULLs replaced). Order by pclass.

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_idsurvivedpclassnamesexagesibspparchfareembarked
103Braund, Mr. Owen Harrismale22107.25S
211Cumings, Mrs. John Bradleyfemale381071.28C
313Heikkinen, Miss. Lainafemale26007.93S

Expected output: avg_raw: 30, avg_filled: 30 (NULL to 30)

Hint

Use COALESCE(age, (SELECT AVG(age) FROM passengers)) to replace NULLs

Concepts

SELECT NULL Handling COALESCE Aggregation GROUP BY Subquery

Practise the topic: SQL practice questions · NULL handling practice · GROUP BY exercises · CTE practice

In these company practice sets

Snowflake

A SQL Quest challenge matched to patterns reported for these companies — not a question any of them has published.

Related questions

Genre Box Office ReportMedium · FreeFare Imputation AnalysisMedium · FreeLEFT JOIN NULL Semantics: Inactive CustomersMedium · FreeManagement Hierarchy OverviewMedium · FreeMembership Tier Revenue AnalysisMedium · FreeSenior Passengers by PortMedium · Free

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