Lessons › SQL › Chapter 9: Data Cleaning
SQL lesson
NULLIF() for converting placeholder values to NULL
Some tables use stand-ins like 'N/A' or 999 for unknown. They look real, so they spoil totals and averages. NULLIF(brand, 'N/A') shows NULL where brand is 'N/A', and keeps every other value.
Try this lesson free →Example
Turn fake values into empty cells
SELECT product_id,
NULLIF(brand, 'N/A') AS clean_brand,
category,
NULLIF(price, 999) AS clean_price,
NULLIF(stock_count, 999) AS clean_stock
FROM products| product_id | clean_brand | category | clean_price | clean_stock |
|---|---|---|---|---|
| P2001 | NovaTech | Electronics | 129.99 | 45 |
| P2002 | Clothing | 34.5 | ||
| P2003 | GlowUp | Beauty | 12 | |
| P2004 | FreshBasket | Grocery | 5.99 | 200 |
| P2005 | Fashion | 89.0 |
Step by step
- Some tables use stand-ins like 'N/A' or 999 for "unknown".
SELECT product_id, NULLIF(brand, 'N/A') AS clean_brand, category, NULLIF(price, 999) AS clean_price, NULLIF(stock_count, 999) AS clean_stock FROM products - If brand is 'N/A', show NULL. Otherwise show brand.
SELECT product_id, NULLIF(brand, 'N/A') AS clean_brand, category, NULLIF(price, 999) AS clean_price, NULLIF(stock_count, 999) AS clean_stock FROM products - Fake numbers like 999 spoil averages. Empty cells are skipped.
SELECT product_id, NULLIF(brand, 'N/A') AS clean_brand, category, NULLIF(price, 999) AS clean_price, NULLIF(stock_count, 999) AS clean_stock FROM products
Practice
1. Using customers, show customer_id and phone, with the placeholder '000-000-0000' turned into NULL. Name it phone.
SELECT customer_id, NULLIF(phone, '000-000-0000') AS phone FROM customers2. Using products, show product_id and price, with a price of 0 (not priced yet) turned into NULL. Name it price.
SELECT product_id, NULLIF(price, 0) AS price FROM products3. Using orders, show order_id and revenue, with a revenue of 0 turned into NULL. Name it revenue.
SELECT order_id, NULLIF(revenue, 0) AS revenue FROM orders4. Using inventory, show product_id and warehouse, with the placeholder 'UNKNOWN' turned into NULL. Name it warehouse.
SELECT product_id, NULLIF(warehouse, 'UNKNOWN') AS warehouse FROM inventory5. Using reviews, show review_id and rating, with a rating of 0 turned into NULL. Ratings go from 1 to 5, so 0 means 'not rated'. Name it rating.
SELECT review_id, NULLIF(rating, 0) AS rating 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 →