Lessons › SQL › Deep Dive: Data Cleaning
SQL lesson
IS NULL and COALESCE() for missing data
IS NULL finds every spot in your data where a value was never recorded - nothing slipped in, not even a zero or a blank space, just pure emptiness. COALESCE then fills those gaps with a fallback you choose.
Try this lesson free →Example
Finding and Filling Missing Retail Values
SELECT order_id, customer_id, COALESCE(discount, 0) AS discount, COALESCE(region, 'Unknown') AS region, ship_date
FROM orders| order_id | customer_id | discount | region | ship_date |
|---|---|---|---|---|
| O2001 | C101 | 10.0 | Northeast | 2024-03-05 |
| O2002 | C102 | 0 | Southwest | 2024-03-06 |
| O2003 | C103 | 5.0 | Unknown | 2024-03-07 |
| O2004 | C104 | 0 | Midwest | |
| O2005 | C105 | 15.0 | Southeast | 2024-03-09 |
Step by step
- Run the query without COALESCE so you can see what the unfiltered values look like.
SELECT order_id, customer_id, discount, COALESCE(region, 'Unknown') AS region, ship_date FROM orders; - COALESCE returns the first non-NULL value from the arguments.
SELECT order_id, customer_id, COALESCE(discount, 0), COALESCE(region, 'Unknown') AS region, ship_date FROM orders; - AS gives the COALESCE result a friendly column name so the output reads cleanly.
SELECT order_id, customer_id, COALESCE(discount, 0) AS discount, COALESCE(region, 'Unknown') AS region, ship_date FROM orders;
Practice
1. Using customers, write a query that returns customer_id or 'Unknown' when customer_id is NULL.
SELECT COALESCE(customer_id, 'Unknown') FROM customers2. Using products, write a query that returns brand or 'Unknown' when brand is NULL.
SELECT COALESCE(brand, 'Unknown') FROM products3. Using orders, write a query that returns revenue or 0 when revenue is NULL.
SELECT COALESCE(revenue, 0) FROM orders4. Using inventory, write a query that returns stock_count or 0 when stock_count is NULL.
SELECT COALESCE(stock_count, 0) FROM inventory5. Using reviews, write a query that returns review_id or 'Unknown' when review_id is NULL.
SELECT COALESCE(review_id, 'Unknown') FROM reviewsLearn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.
Try this lesson free →