सामग्री पर जाएँ

लेसन 21 · Cleaning in SQL and Spreadsheets

Cleaning Data with SQL

Clean data in SQL with TRIM, LOWER, NULLIF, CASE, safe type conversion and mapping tables, while keeping raw tables unchanged behind staging views.

When data already lives in a database, cleaning it there avoids exporting copies and can handle large tables. The same principles apply: keep raw data, write rules that can be run again and count what changes. The examples here run on SQLite. Function names and type behavior differ between database systems, so check your database's documentation.

Raw, staging, clean

A common layout uses a raw table loaded exactly as received (often all text), a staging view or table that applies rules, and a clean table that others query. A normal view stores a query rather than a copy of the data, so it reflects the current raw table.

Trim, case and empty strings

TRIM removes spaces at both ends. In SQLite it does not remove tabs or non-breaking spaces unless you list them. NULLIF(a, b) returns NULL when the two are equal, which turns empty text into a true missing value.

SQL Standardize text and missing markers

Press Run (or Ctrl + Enter) to see the result here.

By default, SQLite's LOWER and UPPER change only ASCII letters. Other databases follow their own rules. See string functions and COALESCE and NULLIF.

NULL behaves differently

NULL means unknown or absent. Comparing it with = yields unknown, not true, so use IS NULL. Aggregates such as AVG and SUM ignore NULL values. COUNT(*) counts rows, while COUNT(column) counts non-null values.

SQL Count missing values per column

Press Run (or Ctrl + Enter) to see the result here.

Convert types carefully

Many databases raise an error when a cast of bad text fails, and some offer a "try" version that returns NULL. SQLite's CAST does not raise: CAST('12abc' AS INTEGER) returns 12, and CAST('abc' AS INTEGER) returns 0. So check the pattern before casting. In SQLite, GLOB tests simple patterns.

SQL Validate before casting

Press Run (or Ctrl + Enter) to see the result here.

The pattern *[^0-9]* means "contains something that is not a digit". The rule accepts only digits, so only whole, non-negative numbers. Compare the two results: the blind cast invents values.

Mapping tables

Use a join to a mapping table instead of a long CASE expression. A LEFT JOIN keeps unmapped rows so you can find them.

SQL Map categories and list unknowns

Press Run (or Ctrl + Enter) to see the result here.

The primary key on the mapping table allows only one row per variant, so this join cannot multiply rows.

Updating in place

Prefer creating cleaned views or tables over changing raw data. When you must run UPDATE or DELETE:

  1. Run a SELECT with the same WHERE clause first.
  2. Work inside a transaction.
  3. Check the number of affected rows.
  4. Commit only if it matches your expectation. Otherwise roll back.
  5. Make sure important tables have a backup.
SQL
BEGIN;
UPDATE customers SET city = 'New York' WHERE LOWER(TRIM(city)) = 'nyc';
-- check the affected row count, then:
COMMIT;   -- or ROLLBACK;

This snippet is read-only because it has no table here. Transaction syntax varies between databases. Get approval before you change shared or production data.

Regular expressions and dates

Regular expression support varies widely. Plain SQLite does not include a built-in REGEXP function. Date functions also differ, and SQLite works best with ISO text such as 2026-03-04. For complex parsing, you may find Python easier. See data cleaning in SQL for more examples.

Common mistake: an UPDATE with a missing or wrong WHERE clause. Without one, it changes every row. Always preview first.

Profile before you clean

SQL is also a quick profiling tool. For a text column, group by '[' || column || ']' and count. The brackets make leading and trailing spaces visible. LENGTH(column) helps you find values that are unexpectedly short or long, and MIN and MAX show the ends of a column. Remember that on text, they compare characters, so '100' sorts before '9'.

Keep rules in one place

If five reports each trim and map a column in their own way, they will eventually disagree. Put the rule in one view or one scheduled transformation and let every report read from it. When the rule changes, you change it once and test it once.

Views recalculate when queried, which keeps them current but can be slow on large tables. A table that you rebuild on a schedule is faster to query but can be out of date. Show the refresh time so readers know what they are seeing.

Empty text and NULL

Systems differ in how they treat empty strings. Oracle, for example, treats a zero-length string as NULL, while SQLite and many other databases keep them separate. If you move queries between systems, test your missing-value rules again.

An order for your rules

Apply rules in a sensible sequence inside your staging layer. First remove technical noise, such as outer spaces and empty strings. Next convert missing markers to NULL. Then validate patterns and convert types. Finally map categories and check relationships. Later steps are simpler when earlier ones have already run.

Chained views or common table expressions let you name each stage. When a result looks wrong, you can query one stage at a time and see where the value changed. Keep the raw column next to the cleaned column in staging while you develop, so that every difference is visible. You can leave it out of the final table once the rules are tested.

Describe your views

Add a short comment above each cleaning query that states what it assumes about the raw table, such as the date format or the missing markers. When the source changes, these comments show you which assumption broke.

Check your understanding

Quick check · 3 questions

of 3 answered You scored / 3 · perfect!

  1. 1. What does NULLIF(TRIM(city), '') return for a blank city?

    NULLIF returns NULL when both arguments are equal.
  2. 2. Why check the pattern before casting in SQLite?

    SQLite converts a leading number or returns 0 instead of failing.
  3. 3. Why use a LEFT JOIN with a mapping table?

    An inner join would silently drop unmapped records.

Summary

  • Keep raw tables and clean through views or new tables.
  • Use TRIM, LOWER, NULLIF and CASE for standard rules.
  • Validate before casting and join mapping tables with LEFT JOIN.
  • Preview data changes and wrap them in transactions.

Next: Deduplicating and Validating in SQL

आपकी प्रगति इसी ब्राउज़र में सेव होती है। खाते की ज़रूरत नहीं है।