AlgoPlusAlgoPlus
Learn/Databases
Lesson

Integrity Constraints

Rules the database refuses to break — entity integrity, referential integrity, and domain constraints — checked on every change.

8 min read Watch it move Build it

Integrity constraints are rules about valid data that the database enforces *itself*, rejecting any insert, update, or delete that would break them. You never have to trust application code to keep the data clean — the DBMS checks automatically on every change. Three kinds do most of the work: entity integrity, referential integrity, and domain constraints.

The three core rules

  1. 1Entity integrity — every row must be identifiable: its primary key must be unique and never NULL.
  2. 2Referential integrity — links between tables must be real: a foreign key must reference a row that actually exists in the other table (or be NULL).
  3. 3Domain constraint — each column only accepts sensible values from its allowed type or set (an age must be a non-negative number).

A worked example — orders and customers

CREATE TABLE Customer (
  cust_id INT PRIMARY KEY,           -- entity integrity: unique, not NULL
  name    VARCHAR(60) NOT NULL
);
CREATE TABLE Orders (
  order_id INT PRIMARY KEY,
  cust_id  INT REFERENCES Customer(cust_id),  -- referential integrity
  amount   INT CHECK (amount >= 0)             -- domain constraint
);
What a violation looks like
INSERT INTO Orders VALUES (7, 999, 50) when no customer 999 exists is rejected — a foreign key can't dangle. INSERT INTO Customer VALUES (NULL, 'Rae') is rejected — a primary key can't be NULL. ... amount = -5 is rejected by the CHECK domain constraint.

What happens when you delete a referenced row

If you delete customer 42 while orders still point at them, referential integrity would break. The DBMS follows the referential action you declared: RESTRICT blocks the delete, CASCADE deletes the dependent orders too, and SET NULL clears the foreign key to mean 'not linked'.

Constraints are cheaper than clean-up
Letting the database reject bad data at write time is far cheaper than discovering — months later — that some orders point at customers who never existed. The rule lives with the data, not scattered across every app that touches it.
Check yourself
You run INSERT INTO Orders(order_id, cust_id, amount) VALUES (7, 999, 50) but no customer with id 999 exists. What happens and why?