SQL NOT NULL, UNIQUE, CHECK and DEFAULT
What you will learn
- How
NOT NULL,UNIQUE,CHECKandDEFAULTwork - How to write a rule over several columns
- How to name a rule
- How to test a rule by trying to break it
This lesson runs on the sample database you chose in lesson 1.1 (use the Example data picker at the top). The tables you create exist only in your browser's copy of the data; Reset data removes them. Run the cells from top to bottom. (Database Fundamentals, lesson 2.7, explains why these rules matter.)
1. A table with rules
A constraint is a rule the database checks on every insert and update. When a row breaks it, the change is refused and nothing is saved:
CREATE TABLE lib_members (
member_id INTEGER PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
name TEXT NOT NULL,
age INTEGER CHECK (age BETWEEN 0 AND 130),
status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'paused', 'left')),
joined_on TEXT NOT NULL DEFAULT '2026-01-01'
);
INSERT INTO lib_members (email, name, age) VALUES ('rina@example.com', 'Rina', 25);
SELECT * FROM lib_members;
member_id email name age status joined_on
--------- ---------------- ---- --- ------ ----------
1 rina@example.com Rina 25 active 2026-01-01
(1 row)
CREATE TABLE lib_members (
member_id INTEGER PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
name TEXT NOT NULL,
age INTEGER CHECK (age BETWEEN 0 AND 130),
status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'paused', 'left')),
joined_on TEXT NOT NULL DEFAULT '2026-01-01'
);
INSERT INTO lib_members (email, name, age) VALUES ('rina@example.com', 'Rina', 25);
SELECT * FROM lib_members;
member_id email name age status joined_on
--------- ---------------- ---- --- ------ ----------
1 rina@example.com Rina 25 active 2026-01-01
(1 row)
CREATE TABLE lib_members (
member_id INTEGER PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
name TEXT NOT NULL,
age INTEGER CHECK (age BETWEEN 0 AND 130),
status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'paused', 'left')),
joined_on TEXT NOT NULL DEFAULT '2026-01-01'
);
INSERT INTO lib_members (email, name, age) VALUES ('rina@example.com', 'Rina', 25);
SELECT * FROM lib_members;
member_id email name age status joined_on
--------- ---------------- ---- --- ------ ----------
1 rina@example.com Rina 25 active 2026-01-01
(1 row)
What each rule does:
| Rule | Meaning |
|---|---|
NOT NULL |
the column must have a value |
UNIQUE |
no two rows may share the value |
CHECK (condition) |
the condition must be true (or unknown) |
DEFAULT value |
the value used when the column is left out |
The row got its status and joined_on from the defaults.
2. Break each rule
A rule you never tested is only a hope. Try to break each one:
A repeated email (UNIQUE):
INSERT INTO lib_members (email, name) VALUES ('rina@example.com', 'Another Rina');
IntegrityError: UNIQUE constraint failed: lib_members.email
A missing name (NOT NULL):
INSERT INTO lib_members (email) VALUES ('nobody@example.com');
IntegrityError: NOT NULL constraint failed: lib_members.name
An impossible age (CHECK):
INSERT INTO lib_members (email, name, age) VALUES ('old@example.com', 'Old', 200);
IntegrityError: CHECK constraint failed: age BETWEEN 0 AND 130
A status that is not in the list (CHECK):
INSERT INTO lib_members (email, name, status) VALUES ('odd@example.com', 'Odd', 'dancing');
IntegrityError: CHECK constraint failed: status IN ('active', 'paused', 'left')
A repeated email (UNIQUE):
INSERT INTO lib_members (email, name) VALUES ('rina@example.com', 'Another Rina');
IntegrityError: UNIQUE constraint failed: lib_members.email
A missing name (NOT NULL):
INSERT INTO lib_members (email) VALUES ('nobody@example.com');
IntegrityError: NOT NULL constraint failed: lib_members.name
An impossible age (CHECK):
INSERT INTO lib_members (email, name, age) VALUES ('old@example.com', 'Old', 200);
IntegrityError: CHECK constraint failed: age BETWEEN 0 AND 130
A status that is not in the list (CHECK):
INSERT INTO lib_members (email, name, status) VALUES ('odd@example.com', 'Odd', 'dancing');
IntegrityError: CHECK constraint failed: status IN ('active', 'paused', 'left')
A repeated email (UNIQUE):
INSERT INTO lib_members (email, name) VALUES ('rina@example.com', 'Another Rina');
IntegrityError: UNIQUE constraint failed: lib_members.email
A missing name (NOT NULL):
INSERT INTO lib_members (email) VALUES ('nobody@example.com');
IntegrityError: NOT NULL constraint failed: lib_members.name
An impossible age (CHECK):
INSERT INTO lib_members (email, name, age) VALUES ('old@example.com', 'Old', 200);
IntegrityError: CHECK constraint failed: age BETWEEN 0 AND 130
A status that is not in the list (CHECK):
INSERT INTO lib_members (email, name, status) VALUES ('odd@example.com', 'Odd', 'dancing');
IntegrityError: CHECK constraint failed: status IN ('active', 'paused', 'left')
Each message names the rule: UNIQUE constraint failed: lib_members.email, NOT NULL constraint failed: lib_members.name, CHECK constraint failed: ....
3. CHECK and NULL
A CHECK fails only when its condition is false. If the condition is unknown (because of NULL), the row passes. Our age column allows NULL, so a missing age is accepted:
INSERT INTO lib_members (email, name, age) VALUES ('noage@example.com', 'No Age', NULL);
SELECT name, age FROM lib_members ORDER BY member_id;
name age
------ ----
Rina 25
No Age NULL
(2 rows)
INSERT INTO lib_members (email, name, age) VALUES ('noage@example.com', 'No Age', NULL);
SELECT name, age FROM lib_members ORDER BY member_id;
name age
------ ----
Rina 25
No Age NULL
(2 rows)
INSERT INTO lib_members (email, name, age) VALUES ('noage@example.com', 'No Age', NULL);
SELECT name, age FROM lib_members ORDER BY member_id;
name age
------ ----
Rina 25
No Age NULL
(2 rows)
If a value must always exist, add NOT NULL as well.
4. UNIQUE and NULL
In SQLite a UNIQUE column accepts many NULLs, because two unknowns are not equal (Database Fundamentals, lesson 2.6):
CREATE TABLE lib_phones (phone TEXT UNIQUE);
INSERT INTO lib_phones VALUES (NULL), (NULL), ('0171');
SELECT COUNT(*) AS rows_stored, COUNT(phone) AS with_a_phone FROM lib_phones;
rows_stored with_a_phone
----------- ------------
3 1
(1 row)
CREATE TABLE lib_phones (phone TEXT UNIQUE);
INSERT INTO lib_phones VALUES (NULL), (NULL), ('0171');
SELECT COUNT(*) AS rows_stored, COUNT(phone) AS with_a_phone FROM lib_phones;
rows_stored with_a_phone
----------- ------------
3 1
(1 row)
CREATE TABLE lib_phones (phone TEXT UNIQUE);
INSERT INTO lib_phones VALUES (NULL), (NULL), ('0171');
SELECT COUNT(*) AS rows_stored, COUNT(phone) AS with_a_phone FROM lib_phones;
rows_stored with_a_phone
----------- ------------
3 1
(1 row)
5. A rule over several columns
A CHECK can compare columns of the same row, and a UNIQUE can cover a combination of columns. Write them after the columns:
CREATE TABLE lib_bookings (
booking_id INTEGER PRIMARY KEY,
room TEXT NOT NULL,
day TEXT NOT NULL,
slot INTEGER NOT NULL,
start_day TEXT NOT NULL,
end_day TEXT NOT NULL,
UNIQUE (room, day, slot),
CHECK (end_day >= start_day)
);
INSERT INTO lib_bookings (room, day, slot, start_day, end_day) VALUES ('A', 'Mon', 1, '2026-03-01', '2026-03-05');
(1 row changed)
The same room, day and slot twice is refused:
INSERT INTO lib_bookings (room, day, slot, start_day, end_day) VALUES ('A', 'Mon', 1, '2026-04-01', '2026-04-02');
IntegrityError: UNIQUE constraint failed: lib_bookings.room, lib_bookings.day, lib_bookings.slot
An end before the start is refused:
INSERT INTO lib_bookings (room, day, slot, start_day, end_day) VALUES ('B', 'Mon', 1, '2026-03-10', '2026-03-02');
IntegrityError: CHECK constraint failed: end_day >= start_day
CREATE TABLE lib_bookings (
booking_id INTEGER PRIMARY KEY,
room TEXT NOT NULL,
day TEXT NOT NULL,
slot INTEGER NOT NULL,
start_day TEXT NOT NULL,
end_day TEXT NOT NULL,
UNIQUE (room, day, slot),
CHECK (end_day >= start_day)
);
INSERT INTO lib_bookings (room, day, slot, start_day, end_day) VALUES ('A', 'Mon', 1, '2026-03-01', '2026-03-05');
(1 row changed)
The same room, day and slot twice is refused:
INSERT INTO lib_bookings (room, day, slot, start_day, end_day) VALUES ('A', 'Mon', 1, '2026-04-01', '2026-04-02');
IntegrityError: UNIQUE constraint failed: lib_bookings.room, lib_bookings.day, lib_bookings.slot
An end before the start is refused:
INSERT INTO lib_bookings (room, day, slot, start_day, end_day) VALUES ('B', 'Mon', 1, '2026-03-10', '2026-03-02');
IntegrityError: CHECK constraint failed: end_day >= start_day
CREATE TABLE lib_bookings (
booking_id INTEGER PRIMARY KEY,
room TEXT NOT NULL,
day TEXT NOT NULL,
slot INTEGER NOT NULL,
start_day TEXT NOT NULL,
end_day TEXT NOT NULL,
UNIQUE (room, day, slot),
CHECK (end_day >= start_day)
);
INSERT INTO lib_bookings (room, day, slot, start_day, end_day) VALUES ('A', 'Mon', 1, '2026-03-01', '2026-03-05');
(1 row changed)
The same room, day and slot twice is refused:
INSERT INTO lib_bookings (room, day, slot, start_day, end_day) VALUES ('A', 'Mon', 1, '2026-04-01', '2026-04-02');
IntegrityError: UNIQUE constraint failed: lib_bookings.room, lib_bookings.day, lib_bookings.slot
An end before the start is refused:
INSERT INTO lib_bookings (room, day, slot, start_day, end_day) VALUES ('B', 'Mon', 1, '2026-03-10', '2026-03-02');
IntegrityError: CHECK constraint failed: end_day >= start_day
6. Name your rules
Give a rule a name and the error message says which one failed:
CREATE TABLE lib_savings (
savings_id INTEGER PRIMARY KEY,
balance_cents INTEGER NOT NULL,
CONSTRAINT balance_not_negative CHECK (balance_cents >= 0)
);
(done)
INSERT INTO lib_savings (balance_cents) VALUES (-100);
IntegrityError: CHECK constraint failed: balance_not_negative
CREATE TABLE lib_savings (
savings_id INTEGER PRIMARY KEY,
balance_cents INTEGER NOT NULL,
CONSTRAINT balance_not_negative CHECK (balance_cents >= 0)
);
(done)
INSERT INTO lib_savings (balance_cents) VALUES (-100);
IntegrityError: CHECK constraint failed: balance_not_negative
CREATE TABLE lib_savings (
savings_id INTEGER PRIMARY KEY,
balance_cents INTEGER NOT NULL,
CONSTRAINT balance_not_negative CHECK (balance_cents >= 0)
);
(done)
INSERT INTO lib_savings (balance_cents) VALUES (-100);
IntegrityError: CHECK constraint failed: balance_not_negative
7. Rules in the database, too
Your program should check input and give friendly messages. But the database enforces the rule for everything: the website, a script, a manual fix at midnight. Put the rules that must never be broken in the table. Write rules that are always true (a balance is not negative), not guesses (a name is under 20 letters).
The Shop's own rules, listed from its table definitions:
SELECT name, "notnull", dflt_value FROM pragma_table_info('products') WHERE "notnull" = 1 OR dflt_value IS NOT NULL;
name notnull dflt_value
----------- ------- ----------
sku 1 NULL
name 1 NULL
category_id 1 NULL
supplier_id 1 NULL
price 1 NULL
cost 1 NULL
stock 1 0
is_active 1 1
added_on 1 NULL
(9 rows)
The Bank's own rules (not-null columns and defaults):
SELECT name, "notnull", dflt_value FROM pragma_table_info('accounts') WHERE "notnull" = 1 OR dflt_value IS NOT NULL;
name notnull dflt_value
------------- ------- ----------
customer_id 1 NULL
branch_id 1 NULL
account_type 1 NULL
opened_on 1 NULL
status 1 'open'
balance_cents 1 NULL
(6 rows)
The School's own rules (not-null columns and defaults):
SELECT name, "notnull", dflt_value FROM pragma_table_info('enrollments') WHERE "notnull" = 1 OR dflt_value IS NOT NULL;
name notnull dflt_value
----------- ------- ----------
student_id 1 NULL
section_id 1 NULL
enrolled_on 1 NULL
(3 rows)
Worked example: add the rules to a description
"A product has a name, a price above zero, a stock count that is never negative (default 0), and a size that is S, M or L (or unknown)."
| Column | Definition |
|---|---|
name |
TEXT NOT NULL |
price |
REAL NOT NULL CHECK (price > 0) |
stock |
INTEGER NOT NULL DEFAULT 0 CHECK (stock >= 0) |
size |
TEXT CHECK (size IN ('S', 'M', 'L')) (may be NULL) |
Then test each rule with a row that breaks it. The description is made up.
Common mistakes
- Rules only in the program, where other tools bypass them.
- A
CHECKthat is too strict for real data. - Forgetting that
NULLpasses aCHECK. UNIQUEon a column whereNULLs are many and then expecting only one.- Never testing the rules.
Key takeaways
NOT NULL,UNIQUE,CHECKandDEFAULTput the rules in the table.- A broken rule refuses the change and names the rule.
CHECKpasses when the condition is unknown; addNOT NULLwhen needed.- Rules can cover several columns and can be named.
- Test every rule by trying to break it.
Practice
1. Write a column for a rating that must be from 1 to 5.
Show answer
rating INTEGER NOT NULL CHECK (rating BETWEEN 1 AND 5)
2. What does DEFAULT 'active' do?
Show answer
When an insert leaves the column out, the value is 'active'.
3. Does a row with age NULL pass CHECK (age BETWEEN 0 AND 130)?
Show answer
Yes, because the condition is unknown, not false.
4. How do you make a pair of columns unique together?
Show answer
UNIQUE (a, b) after the column definitions.
5. Why name a constraint?
Show answer
The error message then says which rule was broken.
6. Why keep rules in the database and not only in the program?
Show answer
Other programs, scripts and manual changes can write to the database and would bypass the program's checks.