BBampaa

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

Example

Swap one bit of text

SELECT product_id,
       REPLACE(brand, '/US', '') AS brand_clean,
       category,
       price
FROM products

Result:

product_idbrand_cleancategoryprice
P1001NikeFashion89.99
P1002AdidasFashion74.5
P1003L'OrealBeauty22.0
P1004SamsungElectronics499.99
P1005Levi'sClothing59.95

Step by step

  1. Finds '/US' in brand and swaps it for something else.
    SELECT product_id, REPLACE(brand, '/US', '') AS brand_clean, category, price FROM products
  2. 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
  3. Two quotes with nothing inside means "replace with nothing".
    SELECT product_id, REPLACE(brand, '/US', '') AS brand_clean, category, price FROM products

Practice

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

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 products
2. 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 customers
3. 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 suppliers
4. 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 employees
5. 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 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