Lessons › SQL › Chapter 9: Data Cleaning
SQL lesson
Standardizing categories with CASE WHEN and LOWER()
The same category can be typed many ways: 'Beauty', 'BEAUTY', 'beauty'. LOWER makes them all match. CASE WHEN then turns each one into a single tidy name. ELSE catches anything you didn't list.
Try this lesson free →Example
One spelling for each value
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 'Sports'
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 | Sports |
Step by step
- 'BEAUTY' and 'beauty' both become 'beauty'.
SELECT product_id, CASE WHEN LOWER(category) = 'clothing' THEN 'Clothing' WHEN LOWER(category) = 'beauty' THEN 'Beauty' ELSE 'Other' END AS clean_category FROM products - CASE turns each match into one clean label.
SELECT product_id, CASE WHEN LOWER(category) = 'clothing' THEN 'Clothing' WHEN LOWER(category) = 'beauty' THEN 'Beauty' ELSE 'Other' END AS clean_category FROM products - ELSE handles anything you didn't list.
SELECT product_id, CASE WHEN LOWER(category) = 'clothing' THEN 'Clothing' WHEN LOWER(category) = 'beauty' THEN 'Beauty' ELSE 'Other' END AS clean_category FROM products
Practice
1. Using customers, show customer_id and city in small letters. Name it clean_city.
SELECT customer_id, LOWER(city) AS clean_city FROM customers2. Using customers, show customer_id and city in small letters, with n/a turned into NULL however it's typed. Name it clean_city.
SELECT customer_id, CASE WHEN LOWER(city) = 'n/a' THEN NULL ELSE LOWER(city) END AS clean_city FROM customers3. Using suppliers, show supplier_id and country in small letters, with n/a turned into NULL however it's typed. Name it clean_country.
SELECT supplier_id, CASE WHEN LOWER(country) = 'n/a' THEN NULL ELSE LOWER(country) END AS clean_country FROM suppliers4. Using employees, show employee_id and department, with 'Mktg', 'MKTG' and 'Marketing' all written as 'marketing', and every other department in small letters. Name it clean_department.
SELECT employee_id, CASE WHEN LOWER(department) IN ('mktg', 'marketing') THEN 'marketing' ELSE LOWER(department) END AS clean_department FROM employees5. Using shipments, count how many shipments have each status, with the spelling tidied to small letters. Show clean_status and shipments.
SELECT LOWER(status) AS clean_status, COUNT(*) AS shipments FROM shipments GROUP BY LOWER(status)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 →