BBampaa

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 →
About 5–10 minutes · no sign-up needed

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

Result:

product_idclean_brandcategoryclean_priceclean_stock
P2001NovaTechElectronics129.9945
P2002Clothing34.5
P2003GlowUpBeauty12
P2004FreshBasketGrocery5.99200
P2005Fashion89.0

Step by step

  1. 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
  2. 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
  3. 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

Try each one in your head first, then open the answer.

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 customers
2. 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 products
3. 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 orders
4. 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 inventory
5. 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 reviews

Learn 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 →
About 5–10 minutes · no sign-up needed