Constraints: Protecting Your Data
Constraints are rules the database enforces on every insert and update. Invalid data is rejected with an error.
The 6 main constraints
| Constraint | Rule | Example |
|---|---|---|
NOT NULL | value required | name TEXT NOT NULL |
UNIQUE | no duplicates | email TEXT UNIQUE |
PRIMARY KEY | NOT NULL + UNIQUE id | id … PRIMARY KEY |
FOREIGN KEY | must match a row in another table | user_id INT REFERENCES users(id) |
CHECK | custom condition | CHECK (amount > 0) |
DEFAULT | value when none is given | DEFAULT now() |
Column vs table constraints
- Column level: written after the column —
amount NUMERIC CHECK (amount > 0) - Table level: for rules on several columns —
CHECK (end_date >= start_date),UNIQUE (user_id, name)
Name your constraints
CONSTRAINT positive_amount CHECK (amount > 0) gives clearer error messages and makes them easy to drop later.
UNIQUE details
- Multi-column:
UNIQUE (user_id, name)– each user can have a category name once NULLs are normally not considered equal, so several NULLs are allowed. UseUNIQUE NULLS NOT DISTINCT(PostgreSQL 15+) to allow only one.- Case-insensitive uniqueness: a unique index on
lower(email)(Unit 11)
FOREIGN KEY options (more in Unit 7)
ON DELETE CASCADE– delete children when the parent is deletedON DELETE SET NULL– keep children, clear the linkON DELETE RESTRICT(default behaviour) – block the delete
Why constraints matter
- Bugs, scripts, admin tools and other apps can all bypass your frontend validation
- Constraints keep data consistent forever
- They also document the rules of your data
Rule: validate in the app for nice error messages, enforce in the database for correctness.
Example
CREATE TABLE budgets (
id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
user_id INT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
category TEXT NOT NULL,
amount NUMERIC(10,2) NOT NULL,
start_date DATE NOT NULL,
end_date DATE NOT NULL,
CONSTRAINT positive_amount CHECK (amount > 0),
CONSTRAINT valid_period CHECK (end_date >= start_date),
CONSTRAINT one_budget_per_category UNIQUE (user_id, category, start_date)
);
INSERT INTO budgets (user_id, category, amount, start_date, end_date)
VALUES (1, 'Food', 12000, '2026-11-01', '2026-11-30'); -- ✅
-- Each of these is rejected by the database:
-- ❌ NOT NULL: INSERT INTO budgets (user_id, amount, start_date, end_date) VALUES (1, 500, '2026-11-01', '2026-11-30');
-- ❌ CHECK: ... amount = -500 → violates "positive_amount"
-- ❌ CHECK: ... end_date before start → violates "valid_period"
-- ❌ UNIQUE: same user + category + start_date again
-- ❌ FOREIGN KEY: user_id = 999 → key is not present in table "users"
-- Try one and catch the error safely:
DO $$
BEGIN
INSERT INTO budgets (user_id, category, amount, start_date, end_date)
VALUES (1, 'Travel', -500, '2026-11-01', '2026-11-30');
EXCEPTION WHEN check_violation THEN
RAISE NOTICE 'Rejected: %', SQLERRM; -- Rejected: new row ... violates check constraint "positive_amount"
END $$;
-- See all constraints on a table
SELECT conname, pg_get_constraintdef(oid)
FROM pg_constraint
WHERE conrelid = 'budgets'::regclass;
DROP TABLE budgets;