SQL Data Cleaning Techniques

Why Data Cleaning Matters

Data analysts spend a significant amount of time cleaning data before performing analysis. SQL provides many functions that help standardize, validate, and transform raw data into a consistent format.


Common SQL Data Cleaning Tasks

TaskSQL Function
Remove leading/trailing spacesTRIM()
Convert to uppercaseUPPER()
Convert to lowercaseLOWER()
Replace textREPLACE()
Handle NULL valuesCOALESCE() or IFNULL()
Convert data typesCAST()
Extract part of textLEFT(), RIGHT(), SUBSTRING()
Find textLIKE, INSTR()
Remove duplicatesDISTINCT
Update incorrect valuesUPDATE

Remove Extra Spaces

SELECT TRIM(city)
FROM cities;

Standardize Capitalization

SELECT UPPER(state_code)
FROM cities;
SELECT LOWER(email)
FROM customers;

Replace Characters

SELECT REPLACE(phone,'-','')
FROM customers;

Convert Data Types

SELECT CAST(population AS UNSIGNED)
FROM cities;

Remove Duplicate Records

SELECT DISTINCT city, state
FROM cities;

Handle Missing Values

SELECT COALESCE(state,'Unknown')
FROM cities;

Real-World Example

Before cleaning:

citystate_codepopulation
" seattle "wa1,250,000
"NEW YORK"ny8,258,000

After cleaning:

citystate_codepopulation
SeattleWA1250000
New YorkNY8258000

Example:

SELECT
TRIM(city) AS city,
UPPER(TRIM(state_code)) AS state_code,
REPLACE(population, ',', '') AS population
FROM cities;

Excel vs SQL Data Cleaning

TaskExcelSQL
Remove spacesTRIM()TRIM()
UppercaseUPPER()UPPER()
LowercaseLOWER()LOWER()
Replace charactersSUBSTITUTE()REPLACE()
Convert to numberVALUE()CAST()
Remove duplicatesRemove DuplicatesDISTINCT

Key Takeaways

  • Excel is useful for cleaning small datasets.
  • SQL is better for cleaning large datasets stored in a database.
  • Many data-cleaning concepts are the same in both Excel and SQL.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top