Sub topic 9
Constraints that Protect Data Integrity
This chapter assumes you can read basic SQL, and that you know what tables, primary keys, foreign keys, data types, and NULL are from earlier chapters. Here we focus on how the database itself rejects bad data, which constraints exist, how they behave, and the errors you will meet when you break them.
Why constraints belong in the database
Application code validates input, but applications have bugs, several applications may share one database, and people run ad hoc scripts. A constraint is a rule declared in the schema that the database checks on every INSERT, UPDATE, and DELETE. If a statement would violate the rule, the database rejects the whole statement and changes nothing.
Data integrity means the stored data is correct and consistent with the rules of the domain. Constraints give you three practical benefits:
- The rule is enforced in one place, no matter which program writes the data.
- Bad data is rejected at write time, so readers never have to defend against it.
- The schema documents the rules, and the query planner can sometimes use them.
The sample schema from this tutorial already uses most of them:
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(255) NOT NULL UNIQUE
);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL REFERENCES customers (customer_id),
order_date DATE NOT NULL,
total_amount DECIMAL(10, 2) NOT NULL CHECK (total_amount >= 0)
);The main constraint types
| Constraint | What it enforces | Typical violation |
|---|---|---|
| PRIMARY KEY | Each row has a unique, non-NULL identifier | Inserting a duplicate id |
| NOT NULL | A column must have a value | Omitting `name` on insert |
| UNIQUE | No two rows share the same value (or combination) | Reusing an email address |
| CHECK | A condition on the row must not be false | A negative `total_amount` |
| FOREIGN KEY | A value must match a row in another table | An order for a customer that does not exist |
Each constraint answers a different question. NOT NULL asks "is a value present?", UNIQUE asks "is it different from every other row?", CHECK asks "is it acceptable?", and FOREIGN KEY asks "does the thing it points to exist?".
NOT NULL
By default most columns accept NULL, which means "no value is known". NOT NULL removes that option for a column. Use it whenever a missing value would make the row meaningless or force every query to handle a special case.
INSERT INTO customers (customer_id, name, email)
VALUES (2, NULL, '[email protected]');This fails because name is declared NOT NULL. PostgreSQL reports null value in column "name" violates not-null constraint. Omitting the column from the INSERT has the same effect, unless the column has a DEFAULT.
A sensible habit is to declare columns NOT NULL unless you have a concrete reason for allowing NULL, because it is easier to relax a constraint later than to clean up data that was allowed to go bad.
UNIQUE
A UNIQUE constraint rejects a second row with the same value in the constrained column. In the example, two customers cannot share an email address.
INSERT INTO customers (customer_id, name, email)
VALUES (1, 'Ada Lovelace', '[email protected]');
INSERT INTO customers (customer_id, name, email)
VALUES (3, 'Another Ada', '[email protected]');The second statement fails with a unique violation. Behind the scenes, the database creates an index on the column so it can check for duplicates quickly. That index is a side effect you pay for in storage and write time.
UNIQUE versus PRIMARY KEY
A table has only one primary key, and its columns cannot be NULL. A table can have many UNIQUE constraints. A column that is UNIQUE but not NOT NULL may allow NULLs, as described below.
Unique over several columns
A UNIQUE constraint can span several columns. The combination must be unique, not each column on its own.
CREATE TABLE enrollments (
student_id INTEGER NOT NULL,
course_id INTEGER NOT NULL,
term VARCHAR(10) NOT NULL,
UNIQUE (student_id, course_id, term)
);A student can take many courses and the same course in different terms, but cannot enroll twice in the same course in the same term.
UNIQUE and NULL
In the SQL standard, NULL is not equal to NULL, so two rows with NULL in a UNIQUE column do not conflict. PostgreSQL, MySQL, and SQLite follow this and allow multiple NULLs. SQL Server treats NULLs as equal in a unique constraint and allows only one. PostgreSQL 15 and later also lets you write UNIQUE NULLS NOT DISTINCT to change this. If your logic depends on "at most one row without a value", test your specific database.
CHECK
A CHECK constraint holds a boolean expression that each row must satisfy. The row is rejected only when the expression evaluates to false.
ALTER TABLE orders
ADD CONSTRAINT chk_orders_date CHECK (order_date >= DATE '2000-01-01');Three edge cases cause most confusion:
- NULL passes a CHECK. When a value is NULL, an expression like
total_amount >= 0evaluates to unknown, not false, and the row is accepted. This is whytotal_amountin the example is both NOT NULL and CHECKed. The two constraints work as a pair. - A CHECK sees only its own row. The standard does not allow a CHECK to query other tables or compare against other rows. Rules such as "an order cannot exceed the customer's credit limit" need a foreign key design, a trigger, or application logic.
- Older MySQL ignored CHECK. MySQL versions before 8.0.16 parsed CHECK clauses and silently did nothing. Current versions enforce them.
Good uses of CHECK are value ranges, allowed states, and relationships between columns of the same row:
CREATE TABLE subscriptions (
subscription_id INTEGER PRIMARY KEY,
status VARCHAR(10) NOT NULL
CHECK (status IN ('trial', 'active', 'cancelled')),
starts_on DATE NOT NULL,
ends_on DATE,
CHECK (ends_on IS NULL OR ends_on >= starts_on)
);The last CHECK is written at table level because it involves two columns. Column-level constraints sit next to one column, and table-level constraints appear as separate items in the table definition.
FOREIGN KEY and referential integrity
A foreign key requires that each value in the child column either is NULL or matches an existing value in the referenced parent column. This property is called referential integrity. It prevents orphan rows, such as an order that points to a customer who does not exist.
INSERT INTO orders (order_id, customer_id, order_date, total_amount)
VALUES (101, 999, '2026-02-01', 20.00);This fails if no customer has id 999. The rule also protects the parent side. By default, you cannot delete a customer who still has orders, and you cannot change a referenced key value.
Referential actions
You can tell the database what to do when a referenced parent row is deleted or updated:
| Action | Effect on child rows |
|---|---|
| NO ACTION (default) | The statement fails if children exist |
| RESTRICT | Like NO ACTION, but the check cannot be deferred |
| CASCADE | Delete or update the children too |
| SET NULL | Set the child column to NULL (it must allow NULL) |
| SET DEFAULT | Set the child column to its default value |
CREATE TABLE order_notes (
note_id INTEGER PRIMARY KEY,
order_id INTEGER NOT NULL
REFERENCES orders (order_id) ON DELETE CASCADE,
body VARCHAR(500) NOT NULL
);Deleting an order now also deletes its notes. CASCADE is convenient but dangerous when applied broadly, since one DELETE can remove many rows in many tables. Use it for rows that have no meaning without their parent, like notes or line items. For business records such as orders, the default rejection is usually safer.
Platform gotchas
- SQLite does not enforce foreign keys unless you run
PRAGMA foreign_keys = ON;on each connection. - In MySQL, foreign keys work in InnoDB tables but not in MyISAM.
- A foreign key does not create an index on the child column in PostgreSQL or SQL Server. Without one, deletes on the parent table must scan the child table. This is why the earlier chapter adds
idx_orders_customer_id.
How the database enforces constraints
The exact order of checks varies by database, and you should not rely on it. What matters is that the outcome is all or nothing for the statement. A multi-row INSERT with one bad row stores none of its rows.
Most databases check constraints at the end of each statement. Foreign keys and UNIQUE can often be declared DEFERRABLE (a PostgreSQL feature among others), which postpones the check until COMMIT. This helps when two rows reference each other and must be inserted together.
Naming and changing constraints
If you do not name a constraint, the database invents a name such as orders_total_amount_check. These names differ between systems and make migrations awkward. Name constraints explicitly:
ALTER TABLE orders
ADD CONSTRAINT chk_orders_total_nonneg CHECK (total_amount >= 0);
ALTER TABLE orders
DROP CONSTRAINT chk_orders_total_nonneg;SQLite supports very little ALTER TABLE ... ADD CONSTRAINT, so changes there usually mean recreating the table. In other systems, adding a constraint to a table with existing data makes the database validate every row, which can be slow and will fail if any row already violates the rule. Find violators first:
SELECT order_id, total_amount
FROM orders
WHERE total_amount < 0;Constraints versus application validation
Do not choose one or the other. Validate in the application to give users fast, friendly messages, and keep constraints as the final guarantee. When a constraint does fire, catch the error and translate it. Match on the error code, not the message text. In PostgreSQL, SQLSTATE 23505 means a unique violation, 23503 a foreign key violation, 23502 a not-null violation, and 23514 a check violation.
Constraints cannot express every rule. Rules that span many rows, such as "total stock across warehouses must not go below zero", need transactions with locking, triggers, or application checks. A constraint is not a replacement for those, but it removes a whole class of simple mistakes.
Exercise
A table has discount_percent INTEGER CHECK (discount_percent BETWEEN 0 AND 100), without NOT NULL. Does inserting a row with discount_percent set to NULL succeed, and why? What would you change if every row must have a discount?
Show answer
The insert succeeds. With NULL the CHECK expression evaluates to unknown, not false, and a CHECK rejects a row only when the expression is false. To require a value, add NOT NULL to the column, so that discount_percent INTEGER NOT NULL CHECK (discount_percent BETWEEN 0 AND 100) rejects NULLs as well as out-of-range numbers.
Exercise
An orders.customer_id foreign key uses the default NO ACTION. You run DELETE FROM customers WHERE customer_id = 1; and that customer has two orders. What happens, and what are two ways to make the delete possible?
Show answer
The DELETE fails with a foreign key violation and no rows are removed, because the orders would be left pointing to a missing customer. You can first delete or reassign the customer's orders and then delete the customer, or redefine the foreign key with ON DELETE CASCADE so the orders are deleted automatically (or ON DELETE SET NULL if customer_id allows NULL). Cascade should be chosen only if losing the orders is acceptable.
Exercise
You want each student to have at most one active enrollment per course, but you also want a student to be able to re-enroll after the first enrollment is cancelled. Why does UNIQUE (student_id, course_id) not fit well, and what simple alternative fits a schema that allows one row per term?
Show answer
UNIQUE (student_id, course_id) forbids any second row for the same student and course, so a re-enrollment later would be rejected even after cancellation. Adding the term to the key, as in UNIQUE (student_id, course_id, term), allows one enrollment per course per term while still blocking duplicates within a term.