Database Design Patterns · Lesson 78 of 112

Database Data Quality and Constraints

What you will learn

  • Why data quality is a design job, not a cleaning job
  • The layers: type, NOT NULL, CHECK, UNIQUE, foreign key
  • How to find bad data that is already in a table
  • Why constraints and application checks work together

Untidy data is cheap to prevent and expensive to repair. Lesson 1.1 showed Dhaka and dhaka counted as different cities. This lesson collects the tools that stop such problems and find the ones that got through.

1. Layer 1: types, and the SQLite surprise

This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). It adds small tables of its own to your browser's copy; run the examples from top to bottom, and Reset data starts again.

SQLite is normally forgiving: a column declared INTEGER accepts the word twenty.

CREATE TABLE loose (id INTEGER PRIMARY KEY, age INTEGER, email TEXT);
INSERT INTO loose (age, email) VALUES ('twenty', 'x');
SELECT age, typeof(age) FROM loose;
age     typeof(age)
------  -----------
twenty  text
(1 row)
CREATE TABLE loose (id INTEGER PRIMARY KEY, age INTEGER, email TEXT);
INSERT INTO loose (age, email) VALUES ('twenty', 'x');
SELECT age, typeof(age) FROM loose;
age     typeof(age)
------  -----------
twenty  text
(1 row)
CREATE TABLE loose (id INTEGER PRIMARY KEY, age INTEGER, email TEXT);
INSERT INTO loose (age, email) VALUES ('twenty', 'x');
SELECT age, typeof(age) FROM loose;
age     typeof(age)
------  -----------
twenty  text
(1 row)

A STRICT table (SQLite 3.37 and later) enforces the declared types:

CREATE TABLE strict_t (id INTEGER PRIMARY KEY, age INTEGER) STRICT;
(done)
INSERT INTO strict_t (age) VALUES ('twenty');
IntegrityError: cannot store TEXT value in INTEGER column strict_t.age
INSERT INTO strict_t (age) VALUES ('25');
SELECT age, typeof(age) FROM strict_t;
age  typeof(age)
---  -----------
 25  integer
(1 row)
CREATE TABLE strict_t (id INTEGER PRIMARY KEY, age INTEGER) STRICT;
(done)
INSERT INTO strict_t (age) VALUES ('twenty');
IntegrityError: cannot store TEXT value in INTEGER column strict_t.age
INSERT INTO strict_t (age) VALUES ('25');
SELECT age, typeof(age) FROM strict_t;
age  typeof(age)
---  -----------
 25  integer
(1 row)
CREATE TABLE strict_t (id INTEGER PRIMARY KEY, age INTEGER) STRICT;
(done)
INSERT INTO strict_t (age) VALUES ('twenty');
IntegrityError: cannot store TEXT value in INTEGER column strict_t.age
INSERT INTO strict_t (age) VALUES ('25');
SELECT age, typeof(age) FROM strict_t;
age  typeof(age)
---  -----------
 25  integer
(1 row)

'twenty' is refused; '25' is converted to the number 25. Most other database systems enforce column types by default; SQLite's flexibility is its own choice (lesson 2.2).

Quick check: Name two constraints that stop a row with a missing name or an impossible age from being saved.

NOT NULL on the name column, and CHECK (for example CHECK (age BETWEEN 0 AND 130)) on the age column.

2. Layer 2: all the column rules together

Combine NOT NULL, UNIQUE, CHECK and a case-insensitive collation:

CREATE TABLE people (id INTEGER PRIMARY KEY,
  email TEXT NOT NULL COLLATE NOCASE UNIQUE CHECK (email = trim(email) AND email LIKE '%_@_%._%'),
  age INTEGER CHECK (age BETWEEN 0 AND 130),
  phone TEXT CHECK (phone IS NULL OR (length(phone) = 11 AND phone NOT GLOB '*[^0-9]*')));
INSERT INTO people (email, age, phone) VALUES ('a@x.com', 20, '01711111111');
(1 row changed)

Five more rows, each of which should be refused:

INSERT INTO people (email, age, phone) VALUES ('A@X.COM', 21, NULL);
IntegrityError: UNIQUE constraint failed: people.email
INSERT INTO people (email, age, phone) VALUES (' b@x.com', 22, NULL);
IntegrityError: CHECK constraint failed: email = trim(email) AND email LIKE '%_@_%._%'
INSERT INTO people (email, age, phone) VALUES ('nope', 20, NULL);
IntegrityError: CHECK constraint failed: email = trim(email) AND email LIKE '%_@_%._%'
INSERT INTO people (email, age, phone) VALUES ('c@x.com', 200, NULL);
IntegrityError: CHECK constraint failed: age BETWEEN 0 AND 130
INSERT INTO people (email, age, phone) VALUES ('d@x.com', 30, '0171-11');
IntegrityError: CHECK constraint failed: phone IS NULL OR (length(phone) = 11 AND phone NOT GLOB '*[^0-9]*')
CREATE TABLE people (id INTEGER PRIMARY KEY,
  email TEXT NOT NULL COLLATE NOCASE UNIQUE CHECK (email = trim(email) AND email LIKE '%_@_%._%'),
  age INTEGER CHECK (age BETWEEN 0 AND 130),
  phone TEXT CHECK (phone IS NULL OR (length(phone) = 11 AND phone NOT GLOB '*[^0-9]*')));
INSERT INTO people (email, age, phone) VALUES ('a@x.com', 20, '01711111111');
(1 row changed)

Five more rows, each of which should be refused:

INSERT INTO people (email, age, phone) VALUES ('A@X.COM', 21, NULL);
IntegrityError: UNIQUE constraint failed: people.email
INSERT INTO people (email, age, phone) VALUES (' b@x.com', 22, NULL);
IntegrityError: CHECK constraint failed: email = trim(email) AND email LIKE '%_@_%._%'
INSERT INTO people (email, age, phone) VALUES ('nope', 20, NULL);
IntegrityError: CHECK constraint failed: email = trim(email) AND email LIKE '%_@_%._%'
INSERT INTO people (email, age, phone) VALUES ('c@x.com', 200, NULL);
IntegrityError: CHECK constraint failed: age BETWEEN 0 AND 130
INSERT INTO people (email, age, phone) VALUES ('d@x.com', 30, '0171-11');
IntegrityError: CHECK constraint failed: phone IS NULL OR (length(phone) = 11 AND phone NOT GLOB '*[^0-9]*')
CREATE TABLE people (id INTEGER PRIMARY KEY,
  email TEXT NOT NULL COLLATE NOCASE UNIQUE CHECK (email = trim(email) AND email LIKE '%_@_%._%'),
  age INTEGER CHECK (age BETWEEN 0 AND 130),
  phone TEXT CHECK (phone IS NULL OR (length(phone) = 11 AND phone NOT GLOB '*[^0-9]*')));
INSERT INTO people (email, age, phone) VALUES ('a@x.com', 20, '01711111111');
(1 row changed)

Five more rows, each of which should be refused:

INSERT INTO people (email, age, phone) VALUES ('A@X.COM', 21, NULL);
IntegrityError: UNIQUE constraint failed: people.email
INSERT INTO people (email, age, phone) VALUES (' b@x.com', 22, NULL);
IntegrityError: CHECK constraint failed: email = trim(email) AND email LIKE '%_@_%._%'
INSERT INTO people (email, age, phone) VALUES ('nope', 20, NULL);
IntegrityError: CHECK constraint failed: email = trim(email) AND email LIKE '%_@_%._%'
INSERT INTO people (email, age, phone) VALUES ('c@x.com', 200, NULL);
IntegrityError: CHECK constraint failed: age BETWEEN 0 AND 130
INSERT INTO people (email, age, phone) VALUES ('d@x.com', 30, '0171-11');
IntegrityError: CHECK constraint failed: phone IS NULL OR (length(phone) = 11 AND phone NOT GLOB '*[^0-9]*')

What each rule did:

  • COLLATE NOCASE UNIQUE makes A@X.COM a duplicate of a@x.com.
  • email = trim(email) rejects stray spaces.
  • The LIKE pattern is a rough shape check (something, @, something, a dot, something). Do not try to validate email fully in the database; a real check is sending a confirmation message.
  • phone ... NOT GLOB '*[^0-9]*' means "contains only digits" and the length rule is 11 digits (an example rule for one country's mobile numbers; yours may differ).

3. Layer 3: foreign keys

Relationships are protected by foreign keys (lesson 3.5). Remember SQLite needs PRAGMA foreign_keys = ON for each connection (the cells here already do this); without it, a link to nothing is accepted.

4. Finding bad data that is already there

Constraints cannot fix rows that existed before them. First look, then repair.

CREATE TABLE dirty (id INTEGER PRIMARY KEY, email TEXT, city TEXT);
INSERT INTO dirty (email, city) VALUES ('a@x.com', 'Dhaka'), ('A@x.com ', 'dhaka'), ('b@x.com', 'Dhaka'), (NULL, 'Khulna'), ('c@x.com', '');
SELECT lower(trim(email)) AS email_key, COUNT(*) AS rows_found FROM dirty WHERE email IS NOT NULL GROUP BY email_key HAVING COUNT(*) > 1;
SELECT lower(trim(city)) AS city_key, COUNT(*) AS rows_found FROM dirty GROUP BY city_key ORDER BY city_key;
SELECT id FROM dirty WHERE email IS NULL OR city = '';
email_key  rows_found
---------  ----------
a@x.com             2
(1 row)

city_key  rows_found
--------  ----------
                   1
dhaka              3
khulna             1
(3 rows)

id
--
 4
 5
(2 rows)
CREATE TABLE dirty (id INTEGER PRIMARY KEY, email TEXT, city TEXT);
INSERT INTO dirty (email, city) VALUES ('a@x.com', 'Dhaka'), ('A@x.com ', 'dhaka'), ('b@x.com', 'Dhaka'), (NULL, 'Khulna'), ('c@x.com', '');
SELECT lower(trim(email)) AS email_key, COUNT(*) AS rows_found FROM dirty WHERE email IS NOT NULL GROUP BY email_key HAVING COUNT(*) > 1;
SELECT lower(trim(city)) AS city_key, COUNT(*) AS rows_found FROM dirty GROUP BY city_key ORDER BY city_key;
SELECT id FROM dirty WHERE email IS NULL OR city = '';
email_key  rows_found
---------  ----------
a@x.com             2
(1 row)

city_key  rows_found
--------  ----------
                   1
dhaka              3
khulna             1
(3 rows)

id
--
 4
 5
(2 rows)
CREATE TABLE dirty (id INTEGER PRIMARY KEY, email TEXT, city TEXT);
INSERT INTO dirty (email, city) VALUES ('a@x.com', 'Dhaka'), ('A@x.com ', 'dhaka'), ('b@x.com', 'Dhaka'), (NULL, 'Khulna'), ('c@x.com', '');
SELECT lower(trim(email)) AS email_key, COUNT(*) AS rows_found FROM dirty WHERE email IS NOT NULL GROUP BY email_key HAVING COUNT(*) > 1;
SELECT lower(trim(city)) AS city_key, COUNT(*) AS rows_found FROM dirty GROUP BY city_key ORDER BY city_key;
SELECT id FROM dirty WHERE email IS NULL OR city = '';
email_key  rows_found
---------  ----------
a@x.com             2
(1 row)

city_key  rows_found
--------  ----------
                   1
dhaka              3
khulna             1
(3 rows)

id
--
 4
 5
(2 rows)

The first query finds a duplicate email hiding behind different case and a space. The second shows that Dhaka and dhaka are one city (3 rows) and one blank. The third lists rows with a missing email or a blank city (ids 4 and 5). Cleaning can be a plain UPDATE:

UPDATE dirty SET email = lower(trim(email)), city = lower(trim(city));
SELECT * FROM dirty ORDER BY id;
id  email    city
--  -------  ------
 1  a@x.com  dhaka
 2  a@x.com  dhaka
 3  b@x.com  dhaka
 4  NULL     khulna
 5  c@x.com
(5 rows)
UPDATE dirty SET email = lower(trim(email)), city = lower(trim(city));
SELECT * FROM dirty ORDER BY id;
id  email    city
--  -------  ------
 1  a@x.com  dhaka
 2  a@x.com  dhaka
 3  b@x.com  dhaka
 4  NULL     khulna
 5  c@x.com
(5 rows)
UPDATE dirty SET email = lower(trim(email)), city = lower(trim(city));
SELECT * FROM dirty ORDER BY id;
id  email    city
--  -------  ------
 1  a@x.com  dhaka
 2  a@x.com  dhaka
 3  b@x.com  dhaka
 4  NULL     khulna
 5  c@x.com
(5 rows)

Rows 1 and 2 are now identical duplicates: someone must decide which to keep (and move any links) before a unique rule can be added. Blanks and NULLs need a business decision too, not a guess.

The same look-first habit works on the real tables of the sample database:

Some customers have a city spelled in lower case next to the proper spelling:

SELECT lower(trim(city)) AS city_key, COUNT(DISTINCT city) AS spellings, COUNT(*) AS customers
FROM customers
GROUP BY city_key
HAVING COUNT(DISTINCT city) > 1
ORDER BY customers DESC;
city_key      spellings  customers
------------  ---------  ---------
istanbul              2         32
porto alegre          2         30
nairobi               2         30
lima                  2         29
toronto               2         27
accra                 2         26
hanoi                 2         25
cairo                 2         25
manila                2         18
(9 rows)

Customers who share the same name (after trimming and lower-casing) may be duplicates, or just different people. Only a person can decide:

SELECT lower(trim(full_name)) AS name_key, COUNT(*) AS customers
FROM customers
GROUP BY name_key
HAVING COUNT(*) > 1
ORDER BY customers DESC, name_key
LIMIT 5;
name_key      customers
------------  ---------
amir perez            2
ana nguyen            2
anil mohamed          2
chen eze              2
dev ahmed             2
(5 rows)

Students who share the same full name may be duplicates, or just different people. Only a person can decide:

SELECT lower(trim(first_name || ' ' || last_name)) AS name_key, COUNT(*) AS students
FROM students
GROUP BY name_key
HAVING COUNT(*) > 1
ORDER BY students DESC, name_key
LIMIT 5;
name_key      students
------------  --------
ana yilmaz           2
arjun mahmud         2
chen jensen          2
chloe garcia         2
farid nair           2
(5 rows)

Orphans (rows pointing to a parent that does not exist) are found with a left join, or with SQLite's built-in check. The cells make a parent and a child table without foreign key enforcement, then ask for orphans:

PRAGMA foreign_keys = OFF;
CREATE TABLE p (id INTEGER PRIMARY KEY);
CREATE TABLE ch (id INTEGER PRIMARY KEY, p_id INTEGER REFERENCES p (id));
INSERT INTO ch (p_id) VALUES (99);
SELECT ch.id FROM ch LEFT JOIN p ON p.id = ch.p_id WHERE p.id IS NULL;
id
--
 1
(1 row)
SELECT "table", rowid, parent, fkid FROM pragma_foreign_key_check;
table  rowid  parent  fkid
-----  -----  ------  ----
ch         1  p          0
(1 row)
PRAGMA foreign_keys = ON;
(done)
PRAGMA foreign_keys = OFF;
CREATE TABLE p (id INTEGER PRIMARY KEY);
CREATE TABLE ch (id INTEGER PRIMARY KEY, p_id INTEGER REFERENCES p (id));
INSERT INTO ch (p_id) VALUES (99);
SELECT ch.id FROM ch LEFT JOIN p ON p.id = ch.p_id WHERE p.id IS NULL;
id
--
 1
(1 row)
SELECT "table", rowid, parent, fkid FROM pragma_foreign_key_check;
table  rowid  parent  fkid
-----  -----  ------  ----
ch         1  p          0
(1 row)
PRAGMA foreign_keys = ON;
(done)
PRAGMA foreign_keys = OFF;
CREATE TABLE p (id INTEGER PRIMARY KEY);
CREATE TABLE ch (id INTEGER PRIMARY KEY, p_id INTEGER REFERENCES p (id));
INSERT INTO ch (p_id) VALUES (99);
SELECT ch.id FROM ch LEFT JOIN p ON p.id = ch.p_id WHERE p.id IS NULL;
id
--
 1
(1 row)
SELECT "table", rowid, parent, fkid FROM pragma_foreign_key_check;
table  rowid  parent  fkid
-----  -----  ------  ----
ch         1  p          0
(1 row)
PRAGMA foreign_keys = ON;
(done)

The insert worked only because foreign key enforcement was off; both checks report child row 1 pointing at the missing parent 99. The check row names the child table, the row, the parent table and which foreign key.

5. A strategy

Layer Catches Example
Application friendly messages, complex rules "Enter a valid phone number"
Column type wrong kind of value text in an age column
NOT NULL, DEFAULT missing values no name
CHECK impossible values age 400
UNIQUE duplicates same email twice
Foreign key broken links order for a missing customer
Regular audits what slipped through duplicate and orphan queries

The application checks give good messages; the database constraints are the last line of defence that works for every program, script and manual fix. Use both.

Worked example: a signup table

Before launch, the team writes the table with NOT NULL, a case-insensitive unique email, an age CHECK and a STRICT declaration. A month after launch a monthly job runs the duplicate, blank and orphan queries and mails the counts to the owner. When an import from an old spreadsheet adds messy rows, the constraints refuse the worst and the audit query reveals the rest. Names are made up.

Common mistakes

  • Cleaning forever instead of preventing.
  • Only validating in the browser, while scripts and imports skip it.
  • Over-strict rules (rejecting valid names or emails). Keep checks to facts that are always true.
  • Forgetting PRAGMA foreign_keys = ON in SQLite.
  • Adding a unique rule to a table that already has duplicates without cleaning first.

Key takeaways

  • Data quality is designed in with layers: types, NOT NULL, CHECK, UNIQUE, foreign keys.
  • SQLite types are flexible unless the table is STRICT; foreign keys need switching on.
  • Use constraints as the last line of defence and application checks for friendly messages.
  • Find existing problems with duplicate, blank and orphan queries before adding rules.
  • Keep rules to things that are always true.

Practice

1. What does a STRICT table change in SQLite?

Show answer

It enforces the declared column types, refusing, for example, text in an INTEGER column.

2. Why use both application checks and database constraints?

Show answer

Application checks give friendly messages; constraints protect against every other way data gets in (scripts, imports, other programs).

3. Write a query idea that finds duplicate emails ignoring case and spaces.

Show answer

SELECT lower(trim(email)), COUNT(*) FROM t GROUP BY 1 HAVING COUNT(*) > 1.

4. How do you find orphan rows?

Show answer

Left join the child to the parent and keep rows where the parent side is NULL, or run PRAGMA foreign_key_check in SQLite.

5. Why is a full email check a bad CHECK constraint?

Show answer

Valid email rules are complicated, a rough pattern can reject real addresses, and the only true test is sending a message.

6. You must add UNIQUE on phone to a table that already has duplicate phones. What are the steps?

Show answer

Find the duplicates with a grouped query, decide with the business which row to keep and fix links to the others, clean the data, then add the unique rule.