Lessons › SQL › Chapter 9: Data Cleaning
SQL lesson
REPLACE() for fixing inconsistent values
REPLACE finds a piece of text and swaps it for another. REPLACE(brand, '/US', '') turns 'Nike/US' into 'Nike'. It takes three parts: the column, the text to find, and what to put instead. '' means nothing.
Try this lesson free →Example
Swap one bit of text
SELECT product_id,
REPLACE(brand, '/US', '') AS brand_clean,
category,
price
FROM products| product_id | brand_clean | category | price |
|---|---|---|---|
| P1001 | Nike | Fashion | 89.99 |
| P1002 | Adidas | Fashion | 74.5 |
| P1003 | L'Oreal | Beauty | 22.0 |
| P1004 | Samsung | Electronics | 499.99 |
| P1005 | Levi's | Clothing | 59.95 |
Step by step
- Finds '/US' in brand and swaps it for something else.
SELECT product_id, REPLACE(brand, '/US', '') AS brand_clean, category, price FROM products - The column, the text to find, and what goes in its place.
SELECT product_id, REPLACE(brand, '/US', '') AS brand_clean, category, price FROM products - Two quotes with nothing inside means "replace with nothing".
SELECT product_id, REPLACE(brand, '/US', '') AS brand_clean, category, price FROM products
Practice
1. Using products, show product_id and brand with '/US' removed. Name it brand_clean.
SELECT product_id, REPLACE(brand, '/US', '') AS brand_clean FROM products2. Using customers, show customer_id and phone with the dashes taken out (555-0101 becomes 5550101). Name it phone_digits.
SELECT customer_id, REPLACE(phone, '-', '') AS phone_digits FROM customers3. Using suppliers, show supplier_id and supplier_name with 'Co.' changed to 'Company'. Name it clean_name.
SELECT supplier_id, REPLACE(supplier_name, 'Co.', 'Company') AS clean_name FROM suppliers4. Using employees, show full_name and department, with 'Mktg' changed to 'Marketing'. Name it clean_department.
SELECT full_name, REPLACE(department, 'Mktg', 'Marketing') AS clean_department FROM employees5. Using reviews, show review_id and comment, with '&' changed to 'and'. Name it clean_comment.
SELECT review_id, REPLACE(comment, '&', 'and') AS clean_comment 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 →