← 30 Days of SQL
Day 20 / 30Data Quality

Data Cleaning in SQL

80% of a data analyst's work is cleaning data. These SQL patterns are used daily for ETL, data quality checks, and report prep.

1
Medium

Find duplicate rows in a table.

SQL Answer
-- Find duplicates by email:
SELECT email, COUNT(*) AS cnt
FROM customers
GROUP BY email
HAVING COUNT(*) > 1;

-- See full duplicate rows:
SELECT *
FROM customers
WHERE email IN (
  SELECT email FROM customers
  GROUP BY email HAVING COUNT(*) > 1
);
💡

GROUP BY + HAVING COUNT(*) > 1 identifies duplicates. This is the first step in any data deduplication task — understand the scope before deleting anything.

2
Hard

Delete duplicate rows keeping only the one with the lowest ID.

SQL Answer
DELETE FROM customers
WHERE id NOT IN (
  SELECT MIN(id)
  FROM customers
  GROUP BY email
);

-- MySQL requires subquery workaround:
DELETE FROM customers
WHERE id NOT IN (
  SELECT min_id FROM (
    SELECT MIN(id) AS min_id FROM customers GROUP BY email
  ) tmp
);
💡

Keep one row per email (the one with the smallest id), delete the rest. MySQL doesn't allow deleting from a table you're selecting from directly — hence the nested subquery.

3
Medium

Identify rows where a phone number is not 10 digits.

SQL Answer
SELECT * FROM customers
WHERE LENGTH(REPLACE(phone, ' ', '')) != 10
   OR phone REGEXP '[^0-9]';
💡

Data validation in SQL — check length and format. REPLACE removes spaces first. REGEXP checks for non-numeric characters. Adapt the pattern to your data's phone format.

4
Easy

Standardise inconsistent category names ("sales", "Sales", "SALES" → "Sales").

SQL Answer
-- View the issue:
SELECT DISTINCT department FROM employees;

-- Fix in query (don't modify source):
SELECT INITCAP(LOWER(department)) AS clean_dept
FROM employees;

-- MySQL (no INITCAP): 
SELECT CONCAT(UPPER(LEFT(department,1)), LOWER(SUBSTRING(department,2)))
FROM employees;
💡

LOWER then INITCAP (PostgreSQL) gives proper case. MySQL doesn't have INITCAP — manually uppercase first char. Always prefer fixing at source (UPDATE) over fixing in every query.

5
Medium

Find records where order_date is after ship_date (data quality error).

SQL Answer
SELECT order_id, order_date, ship_date
FROM orders
WHERE ship_date < order_date;
💡

Business rule validation — an order cannot ship before it's placed. These anomaly-detection queries are run as part of data quality pipelines and audits.

EVIKA ACADEMY · SQL FOR DATA ANALYTICS

Want to master SQL with live practice?

Join our SQL for Data Analytics course — live classes in Noida and online across India.

Book Free Demo Class →
← PREVIOUSDay 19: Pivot Tables in SQLNEXT →Day 21: Real-World Scenario: E-commerce Analytics
Best Data Analytics Course in Noida Delhi NCR | EVIKA ACADEMY