Lessons › SQL › Deep Dive: Data Cleaning
SQL lesson
Standardizing categories with CASE WHEN and LOWER()
Combining a case-insensitive conversion with conditional logic lets you collapse messy variations of the same value into one clean, consistent label.
Try this lesson free →Example
Standardizing Retail Categories with CASE WHEN and LOWER()
SELECT product_id, brand, price,
CASE
WHEN LOWER(category) = 'electronics' THEN 'Electronics'
WHEN LOWER(category) = 'clothing' THEN 'Clothing'
WHEN LOWER(category) = 'beauty' THEN 'Beauty'
WHEN LOWER(category) = 'grocery' THEN 'Grocery'
WHEN LOWER(category) = 'sports' THEN 'Fashion'
ELSE 'Other'
END AS clean_category
FROM products| product_id | brand | price | clean_category |
|---|---|---|---|
| P1001 | NovaTech | 299.99 | Electronics |
| P1002 | UrbanWear | 45.0 | Clothing |
| P1003 | GlowUp | 18.5 | Beauty |
| P1004 | FreshMart | 5.75 | Grocery |
| P1005 | ActiveGear | 89.99 | Fashion |
Step by step
- One WHEN/THEN pair handles a single condition; rows that don't match get NULL (or the ELSE if present).
SELECT CASE WHEN LOWER(category) = 'electronics' THEN 'Electronics' ELSE 'Other' END AS category FROM products;; - Add a second WHEN - SQL checks the conditions top-down and uses the first match.
SELECT CASE WHEN LOWER(category) = 'electronics' THEN 'Electronics' WHEN LOWER(category) = 'clothing' THEN 'Clothing' ELSE 'Other' END AS category FROM products;; - Add a third branch the same way. Each WHEN is checked in order; first match wins.
SELECT CASE WHEN LOWER(category) = 'electronics' THEN 'Electronics' WHEN LOWER(category) = 'clothing' THEN 'Clothing' WHEN LOWER(category) = 'beauty' THEN 'Beauty' ELSE 'Other' END AS category FROM products;;
Practice
1. Using customers, write a query that standardizes customer_id by converting it to lowercase and replacing 'n/a' with NULL.
SELECT CASE WHEN LOWER(customer_id) = 'n/a' THEN NULL ELSE LOWER(customer_id) END FROM customers2. Using products, write a query that standardizes brand by converting it to lowercase and replacing 'n/a' with NULL.
SELECT CASE WHEN LOWER(brand) = 'n/a' THEN NULL ELSE LOWER(brand) END FROM products3. Using suppliers, write a query that standardizes country by converting it to lowercase and replacing 'n/a' with NULL.
SELECT CASE WHEN LOWER(country) = 'n/a' THEN NULL ELSE LOWER(country) END FROM suppliers4. Using employees, write a query that standardizes employee_id by converting it to lowercase and replacing 'n/a' with NULL.
SELECT CASE WHEN LOWER(employee_id) = 'n/a' THEN NULL ELSE LOWER(employee_id) END FROM employees5. Using reviews, write a query that standardizes review_id by converting it to lowercase and replacing 'n/a' with NULL.
SELECT CASE WHEN LOWER(review_id) = 'n/a' THEN NULL ELSE LOWER(review_id) END 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 →