Skip to main content
Albero Academy

Constraints

Rules the database enforces to keep data valid.

Data & Schema9 min

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

ConstraintEnforces
NOT NULLA value is required
UNIQUENo duplicate values
PRIMARY KEYUnique + not null — the row identifier
FOREIGN KEYMust reference an existing row in another table
CHECKA custom condition (e.g. price >= 0)
DEFAULTA fallback value when none is given
constraints in action
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

  1. 01Constraints enforce data rules on every write, so invalid data can't be stored.
  2. 02NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK and DEFAULT are the core set.
  3. 03Foreign keys enforce referential integrity; ON DELETE CASCADE removes children.
  4. 04A composite UNIQUE forbids duplicate combinations of columns.

Finished this chapter?

Mark it complete to track your progress through SQL.