Reading history

Data Quality Checks in SQL

5 min read 0 views

A reusable checklist of SQL data quality checks: missing values, out-of-range numbers, orphan rows, messy text duplicates, format checks and constraints.

A report is only as good as the data behind it. Missing values, impossible numbers, rows pointing to records that no longer exist, and the same email typed three different ways all lead to wrong totals and bad decisions. Before analysing a table, experienced analysts run a set of quick data quality checks. This lesson gives you a reusable checklist of SQL queries for the most common problems.

In this lesson you will learn

  • Counting missing values in each column
  • Finding values outside an allowed range
  • Finding orphan rows with a LEFT JOIN
  • Cleaning text with TRIM and LOWER to spot hidden duplicates
  • Simple format checks, and preventing bad data with constraints

You should know NULL values, joins and finding duplicates.

Missing, Out-of-Range and Orphan Rows

-- 1. Missing values in each important column
SELECT COUNT(*)                                  AS total_rows,
       SUM(CASE WHEN cgpa IS NULL THEN 1 ELSE 0 END) AS missing_cgpa,
       SUM(CASE WHEN city IS NULL THEN 1 ELSE 0 END) AS missing_city
FROM students;

-- 2. Values outside the allowed range
SELECT id, name, cgpa FROM students WHERE cgpa < 0 OR cgpa > 4;

-- 3. Orphans: enrollments whose course does not exist
INSERT INTO enrollments VALUES (8, 999, 70);
SELECT e.* FROM enrollments AS e
LEFT JOIN courses AS c ON c.id = e.course_id
WHERE c.id IS NULL;

-- 4. Departments in students that are missing from departments
SELECT DISTINCT dept FROM students
WHERE dept NOT IN (SELECT code FROM departments);

Output

+------------+--------------+--------------+
| total_rows | missing_cgpa | missing_city |
+------------+--------------+--------------+
| 8          | 1            | 0            |
+------------+--------------+--------------+
(1 row)

+----+------+------+
| id | name | cgpa |
+----+------+------+
+----+------+------+
(0 rows)

+------------+-----------+-------+
| student_id | course_id | marks |
+------------+-----------+-------+
| 8          | 999       | 70    |
+------------+-----------+-------+
(1 row)

+------+
| dept |
+------+
+------+
(0 rows)
  1. Completeness. SUM(CASE WHEN col IS NULL THEN 1 ELSE 0 END) counts missing values per column in one pass. One student (Nadia) has no CGPA. COUNT(*) − COUNT(cgpa) gives the same number.
  2. Validity. CGPA must be between 0 and 4. An empty result means the check passed, which is what you want.
  3. Referential integrity. A LEFT JOIN keeps every enrollment; where no course matches, the course columns are NULL. The test row for course 999 is an orphan, pointing to a course that does not exist.
  4. Consistency. Every department code used by students exists in departments, so this check also passes.

Messy Text

-- Messy text: extra spaces and mixed case
CREATE TABLE signups (email TEXT);
INSERT INTO signups VALUES ('rina@mail.com'), (' Rina@Mail.com'), ('karim@mail.com'), ('karim@mail'), ('');

-- How many look like duplicates once cleaned?
SELECT LOWER(TRIM(email)) AS clean_email, COUNT(*) AS copies
FROM signups
GROUP BY clean_email
HAVING COUNT(*) > 1;

-- Simple format check: must contain @ and a dot after it
SELECT email,
       CASE WHEN TRIM(email) = '' THEN 'empty'
            WHEN TRIM(email) NOT LIKE '%_@_%._%' THEN 'bad format'
            ELSE 'ok' END AS check_result
FROM signups;

Output

+---------------+--------+
| clean_email   | copies |
+---------------+--------+
| rina@mail.com | 2      |
+---------------+--------+
(1 row)

+----------------+--------------+
| email          | check_result |
+----------------+--------------+
| rina@mail.com  | ok           |
|  Rina@Mail.com | ok           |
| karim@mail.com | ok           |
| karim@mail     | bad format   |
|                | empty        |
+----------------+--------------+
(5 rows)
  • ” Rina@Mail.com” has a leading space and capitals. After LOWER(TRIM(email)) it equals “rina@mail.com”, so the same person signed up twice.
  • The pattern '%_@_%._%' requires something before the @, something after it, then a dot and at least one more character. “karim@mail” fails because it has no dot after the @.
  • Empty strings are not NULL. Check for both: WHERE email IS NULL OR TRIM(email) = ''.

Pattern checks catch obvious typos only. A real email can only be confirmed by sending a message to it.

Prevent Problems at the Source

ProblemConstraint that prevents it
Missing required valueNOT NULL
Out-of-range numberCHECK (cgpa BETWEEN 0 AND 4)
Orphan rowsFOREIGN KEY … REFERENCES (in SQLite, also turn on PRAGMA foreign_keys = ON)
DuplicatesUNIQUE, ideally on a cleaned value

Checks find problems in data you already have; constraints stop new problems from entering. Use both, and run the checks again after every data import.

Common Mistakes

  1. Using COUNT(column) to count rows. It skips NULLs, which hides the very problem you are looking for.
  2. Using = NULL. It is never true; use IS NULL.
  3. Deleting “bad” rows straight away. First count and inspect them, and keep a backup.
  4. Comparing text without cleaning it. Spaces and capital letters create false “different” values.

Practice Exercises

Exercise 1. Find orders with a missing or non-positive amount, counted per customer.

Show answer
SELECT customer, COUNT(*) AS bad_rows
FROM orders
WHERE amount IS NULL OR amount <= 0
GROUP BY customer;

Only Tuhin, with one order whose amount is NULL.

Exercise 2. Check whether any employee earns more than their manager.

Show answer
SELECT e.name, e.salary
FROM employees AS e
JOIN employees AS m ON m.id = e.manager_id
WHERE e.salary > m.salary;

No rows come back, so the salary structure is consistent.

Frequently Asked Questions

How often should I run data quality checks?

Run them after every import or major change, and on a schedule for important tables. Many teams save the checks as views or scripts and alert someone when a check returns rows.

What is data profiling?

Profiling is a quick summary of each column: row count, number of NULLs, distinct values, minimum, maximum and most common values. It is the first step before writing specific checks.

Summary

  • Check completeness (NULLs), validity (ranges and formats) and referential integrity (orphans).
  • A passing check returns no rows.
  • Clean text with LOWER(TRIM()) before comparing it.
  • Add constraints so bad data cannot enter in the first place.

Next: SQL Project: Library Database.

Lessons are also marked complete when you click Next.

Leave a Reply

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