Stop 14 · SQL for Data AnalysisTopics · 3/9

Data Validation Queries

Part of the SQL Roadmap

In short

Bad data sneaks in through imports, old bugs and missing checks. Validation queries sweep a table for empty fields, impossible values and broken formats.

Validation queries sweep tables for bad data: NULLs in required fields, impossible values, broken formats, orphaned foreign keys and duplicate keys. Running them before analysis stops wrong numbers reaching a report.

The purple blob holds a magnifying glass over a stack of blank marksheets on a desk.

Think of it like this

The board checking marksheets

Before results go out, the board checks every marksheet: marks between 0 and 100, a roll number in the right format, no blank names. One impossible 112 out of 100 means something went wrong upstream.

Watch it happen

Sweeping the users table

riya@test.com, 21
0
NULL, 34
1
amit@test, 19
2
neha@test.com, 250
3
sam@test.com, 28
4

1/5Five user rows: email and age. The app should never allow bad values, but let's check.

The big ideas

What you need to know

Completeness

Required columns must never be NULL or empty.

Range and type

Numbers within allowed limits, dates not in the future when they shouldn't be, prices not negative.

Format

Emails, phone numbers, PIN codes and IDs follow the expected pattern.

Consistency

Related values agree, like an order total matching the sum of its items.

See it in code

Walk through the code

sql
1-- Required fields that are missing2SELECT id FROM users WHERE email IS NULL OR email = '';3 4-- Values outside the allowed range5SELECT id, age FROM users WHERE age < 0 OR age > 120;6 7-- Badly formatted emails (a rough check)8SELECT id, email FROM users WHERE email NOT LIKE '%_@_%._%';

1/3Completeness: NULL and empty string are different, so check both.

Each query should return zero rows. Anything returned is a data bug to investigate.

Save yourself the pain

Common mistakes

Oops

Only validating data you created during your test.

Do this instead

Sweep the whole table. Old imports and past bugs leave bad rows that break new features.

Oops

Treating NULL and empty string as the same.

Do this instead

Check both. email IS NULL and email = '' catch different problems.

Your mission

Write a validation sweep

~25 min

Quick check

Which query finds orders with a negative total?

Go deeper

  1. 1Write checks for NULLs, negative amounts and future dates in an orders table.
  2. 2Find child rows whose parent row is missing with a LEFT JOIN ... IS NULL.
  3. 3Save the checks in one script you can rerun on every new data load.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge