4. Data engineering patterns
4.1 NULL, COALESCE and CASE: clean and label data
Highlights & notes
Select lesson text to highlight it, or tap Add note.
Bookmarks
Bookmark a lesson to see it here.
Raw data is never clean. Values are missing, and codes need labels. Two tools do most of the cleaning work in SQL.
COALESCE(amount, 0)β use amount, but if it is NULL use 0 insteadCASE WHEN ... THEN ... ELSE ... ENDβ SQL's if / else; it builds a new column from rules
CASE checks its rules from top to bottom and stops at the first one that is true. If none is true and there is no ELSE, the result is NULL.
pandas vs SQL
df["amount"].fillna(0)βCOALESCE(amount, 0)np.where(cond, a, b)βCASE WHEN cond THEN a ELSE b END
NULL is not zero and not an empty text. Any maths with NULL gives NULL (5 + NULL is NULL), and SUM and AVG skip it. Decide what a missing value should mean before you replace it.
How it fits together
- Raw column with NULLs
- COALESCE / CASE
- Clean, labelled column
Watch the query run
SQL
SELECT id, COALESCE(amount, 0) AS amount, CASE WHEN amount IS NULL THEN 'missing' WHEN amount >= 10000 THEN 'big' ELSE 'small' END AS sizeFROM ordersWHERE id >= 105;
Rows at this step
id | amount | size ----+--------+-------- 105 | 52000 | big 106 | 650 | small 107 | 11500 | big 108 | 0 | missing
Practice in SQL β Solved
Show each customer's name and city. Where the city is missing, show Unknown. Keep the column name city and sort by name.
Tables you can query: customers, orders
customers id | name | city ---+-------+------ 1 | Asha | Noida 2 | Ravi | Delhi 3 | Meera | Pune 4 | Kabir | Noida 5 | Zoya | NULL orders id | customer_id | product | amount | status | order_date ----+-------------+----------+--------+-----------+----------- 101 | 1 | Laptop | 55000 | delivered | 2026-01-05 102 | 2 | Mouse | 700 | delivered | 2026-01-06 103 | 1 | Keyboard | 1500 | delivered | 2026-01-09 104 | 3 | Monitor | 12000 | cancelled | 2026-01-12 105 | 2 | Laptop | 52000 | delivered | 2026-01-15 106 | 4 | Mouse | 650 | pending | 2026-01-18 107 | 1 | Monitor | 11500 | delivered | 2026-01-20 108 | 3 | Keyboard | NULL | pending | 2026-01-22
Expected output
name | city ------+-------- Asha | Noida Kabir | Noida Meera | Pune Ravi | Delhi Zoya | Unknown
Reference solution
SELECT name,
COALESCE(city, 'Unknown') AS city
FROM customers
ORDER BY name;
Question 1 Β· Easy
What does COALESCE(city, 'Unknown') return when city is NULL?
Question 2 Β· Medium
What is 100 + NULL in SQL?
Question 3 Β· Hard
CASE WHEN amount > 1000 THEN 'big' WHEN amount > 10000 THEN 'huge' ELSE 'small' END. What is the result for 55000?
Key takeaways
COALESCE replaces NULL with a fallback. CASE builds a column from rules and stops at the first true one. NULL is not 0.
Save your progress
Start free and your progress, code and notes stay saved. Free for 1 month, no card needed.
Start free Log in