Data quality checks in SQL: NULLs, ranges, allowed values, duplicates and orphans
ETL & Data Warehouse Testing · 8 questions
Short notes
Key idea
Data quality checks test the target on its own, against rules any good table obeys: completeness, validity, uniqueness, integrity, timeliness. Each query returns the rows that break the rule; zero rows means pass.
Syntax
SELECT COUNT(*) - COUNT(col) FROM t; -- NULLs
SELECT * FROM t WHERE col IS NULL OR col NOT IN ('a','b'); -- allowed values
SELECT * FROM t WHERE x <= 0 OR x > 100000; -- range
SELECT key, COUNT(*) FROM t GROUP BY key HAVING COUNT(*) > 1; -- unique
SELECT * FROM fact f WHERE NOT EXISTS
(SELECT 1 FROM dim d WHERE d.key = f.key); -- orphans
SELECT * FROM t WHERE NOT regexp_matches(col, '^[a-z][*]{3}@'); -- pattern
Example
Shop warehouse: 1 NULL payment method, 2 duplicated order ids, 10 orphan orders (customers 7, 23, 38 were dropped from the dimension because they have no city), 1 unmasked email (critical).
Traps
NULL NOT IN (...)is never true: handle NULL explicitly.- Unique surrogate keys don't mean unique business rows.
- Inner-joined reports silently drop orphans.
- Masking failures are critical, not cosmetic.
Want the full lesson with step-by-step examples, a project and a certificate? ETL & Data Warehouse Testing course, ₹120 →
- Question 1easy
How many NULL payment methods are in the warehouse?
SELECT COUNT(*) - COUNT(payment_method) FROM dw_orders;
- Question 2medium
Order 56's payment_method is NULL. What does this return?
SELECT COUNT(*) FROM dw_orders WHERE payment_method NOT IN ('UPI', 'Card', 'COD', 'NetBanking', 'Unknown'); - Question 3easy
How many rows fail this range check?
SELECT COUNT(*) FROM dw_orders WHERE amount <= 0 OR amount > 100000;
- Question 4medium
order_key is unique in dw_orders, yet two orders are loaded twice. Why doesn't the order_key check catch it?
- Question 5medium
Why save the data quality scorecard (check name, failing rows) after every load?
Data quality checks in SQL: NULLs, ranges, allowed values, duplicates and orphans
Data quality checks in SQL: NULLs, ranges, allowed values, duplicates and orphans
Data quality checks in SQL: NULLs, ranges, allowed values, duplicates and orphans
Data quality checks in SQL: NULLs, ranges, allowed values, duplicates and orphans
Data quality checks in SQL: NULLs, ranges, allowed values, duplicates and orphans
3 more questions on this topic, with hints, and tests
Sign up free for 21 days of every question and test.