Application code has bugs; the database is your last line of defence. Constraints are rules the engine enforces on every write, so invalid data simply cannot be stored no matter which app (or ad-hoc query) tries. Integrity guaranteed in the schema is integrity you never have to hope for.
Integrity in the schema
You met NOT NULL, UNIQUE, DEFAULT and foreign keys earlier. Here we complete the set with CHECK, cascade rules, and multi-column keys — the tools that encode your business rules directly in the table.
CHECK constraints
A CHECK rejects rows that fail a condition (MySQL enforces them from 8.0.16 onward):
CREATE TABLE students (id INT AUTO_INCREMENT PRIMARY KEY,name VARCHAR(100) NOT NULL,package DECIMAL(5,2) CHECK (package >= 0),age INT CHECK (age BETWEEN 16 AND 100));-- INSERT … age = 5 → rejected before it's ever stored
Cascading foreign keys
Foreign keys can specify what happens to child rows when the parent changes. ON DELETE CASCADE deletes the children; ON DELETE SET NULL orphans them safely:
CREATE TABLE enrolments (id INT AUTO_INCREMENT PRIMARY KEY,student_id INT,FOREIGN KEY (student_id) REFERENCES students(id)ON DELETE CASCADE -- delete a student → their enrolments go tooON UPDATE CASCADE);
Composite & unique keys
A key can span several columns. A composite unique key enforces "no duplicate combination" — a student can't enrol in the same programme twice:
ALTER TABLE enrolmentsADD CONSTRAINT uq_student_programme UNIQUE (student_id, programme_id);-- Same student + same programme twice → rejected.
Practice
Add CHECK constraints so package is non-negative and age is sensible. Give a child table an ON DELETE CASCADE foreign key and observe a parent delete removing children. Add a composite unique key preventing duplicate enrolments and confirm the second insert fails.
Key takeaways
- 01Constraints enforce rules on every write, so invalid data cannot be stored by any client.
- 02CHECK rejects rows failing a condition (enforced in MySQL 8.0.16+).
- 03Foreign-key ON DELETE/UPDATE rules (CASCADE, SET NULL, RESTRICT) control what happens to children.
- 04ON DELETE CASCADE is powerful but can delete thousands of rows — use deliberately.
- 05A composite UNIQUE key forbids duplicate combinations of columns.
