Constraints as Safety Rails: NOT NULL, UNIQUE and CHECK

Constraints are rules you attach to a table so the database refuses bad data. I think of them as safety rails on a staircase: you hardly notice them until the moment they stop a fall. This post introduces the common ones with tiny examples.

Comparing database types illustration

A table with rails

CREATE TABLE members (
  id        INTEGER PRIMARY KEY,
  email     TEXT NOT NULL UNIQUE,
  name      TEXT NOT NULL,
  age       INTEGER CHECK (age >= 13),
  club_id   INTEGER REFERENCES clubs(id)
);

Each line after a column name adds a rule. Let us take them one at a time.

NOT NULL: "this must be filled in"

NULL means "no value". NOT NULL refuses rows where that column is empty.

INSERT INTO members (email) VALUES ('a@example.com');
-- fails: name is NOT NULL

Use it for anything your app cannot work without.

UNIQUE: "no two rows may share this"

INSERT INTO members (email, name) VALUES ('a@example.com', 'Ana');
INSERT INTO members (email, name) VALUES ('a@example.com', 'Ann');
-- second insert fails: email must be unique

Perfect for emails, usernames and codes that must not repeat.

CHECK: "this must satisfy a condition"

INSERT INTO members (email, name, age) VALUES ('b@example.com', 'Ben', 9);
-- fails: CHECK (age >= 13)

Good for simple ranges and allowed values, such as CHECK (status IN ('active', 'paused')).

PRIMARY KEY: "this identifies the row"

A primary key is both NOT NULL and UNIQUE, plus a promise that this is *the* identifier for each row.

FOREIGN KEY: "this must point to something real"

REFERENCES clubs(id) means club_id must match an existing club, or be empty. You cannot assign a member to club 99 if there is no club 99. In SQLite, remember to switch enforcement on with PRAGMA foreign_keys = ON; for each connection; other databases enforce foreign keys by default.

Why not just check in the app?

You should check in the app too, to give friendly messages. But constraints in the database catch problems your app misses: a second program writing to the same database, a quick fix typed by hand, a bug in a new feature, or two users signing up with the same email at the same instant. The database is the last line of defence.

Summary table

ConstraintStopsExample
NOT NULLMissing valuesA member without a name
UNIQUEDuplicatesTwo accounts with one email
CHECKValues outside a ruleA negative price
PRIMARY KEYRows without a reliable identityTwo rows with id 5
FOREIGN KEYLinks to nothingAn order for a customer who does not exist

A gentle suggestion

When you design a table, go through each column and ask: must it be filled in? Must it be unique? Is there a range or list of allowed values? Does it point to another table? Add the rails now; it is harder to add them after bad data has crept in. Our page on reading your first database error message shows what you will see when a rail does its job.

A free learning page for beginners. Practise on a test database, never on real customer data, and check the official documentation for your database version.

Related pages on this site