Constraints are rules the database enforces on every write, so invalid data simply can't be stored — no matter which app or query tries. Integrity guaranteed in the schema is integrity you never have to hope for.
The core constraints
| Constraint | Enforces |
|---|---|
NOT NULL | A value is required |
UNIQUE | No duplicate values |
PRIMARY KEY | Unique + not null — the row identifier |
FOREIGN KEY | Must reference an existing row in another table |
CHECK | A custom condition (e.g. price >= 0) |
DEFAULT | A fallback value when none is given |
CREATE TABLE enrolments (id INT PRIMARY KEY,student_id INT NOT NULL,programme_id INT NOT NULL,fee DECIMAL(8,2) CHECK (fee >= 0),FOREIGN KEY (student_id) REFERENCES students(id) ON DELETE CASCADE,UNIQUE (student_id, programme_id) -- no duplicate enrolment);
Key takeaways
- 01Constraints enforce data rules on every write, so invalid data can't be stored.
- 02NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK and DEFAULT are the core set.
- 03Foreign keys enforce referential integrity; ON DELETE CASCADE removes children.
- 04A composite UNIQUE forbids duplicate combinations of columns.
