NULL means unknown. col = NULL is never true, so use IS NULL / IS NOT NULL.
Four options: remove the row, replace with a default (COALESCE), impute (mean, median, previous value), or flag it.
For ML: impute, then keep a missing-indicator column. The fact that a value is missing is often a signal.
11Basic
Count, filter and default
answer-1.sql
1-- 1. How many ages are missing?2SELECTCOUNT(*)-COUNT(age)ASmissing_age3FROMstudents;45-- 2. Treat a missing grade as "Ungraded"6SELECTname,COALESCE(grade,'Ungraded')ASgrade7FROMstudents;89-- 3. Keep only complete rows (read-only, nothing is deleted)10SELECT*11FROMstudents12WHEREageISNOTNULL;
Downside: dropping rows loses data and can bias the training set
22Optimized
Impute per group and keep a missing flag
answer-2.sql
1-- Group mean as a window function: every row stays2SELECTid,name,3COALESCE(age,ROUND(AVG(age)OVER(PARTITIONBYdepartment)))ASage_filled,4CASEWHENageISNULLTHEN1ELSE0ENDASage_was_missing5FROMstudents;67-- Skewed data? Use the median instead of the mean8WITHmedAS(9SELECTdepartment,10PERCENTILE_CONT(0.5)WITHINGROUP(ORDERBYage)ASmedian_age11FROMstudents12GROUPBYdepartment13)14SELECTs.id,s.name,COALESCE(s.age,m.median_age)ASage_filled15FROMstudentss16LEFTJOINmedmONm.department=s.department;
Why: keeps every row
the flag becomes a feature
AVG ignores NULLs, so it is the mean of the known ages
Fit imputation values on training data only
Log in to mark questions completed and keep your streak.