Home/Labs/Relational Integrity Constraints
All 280 Labs
INTERACTIVE LAB🛡️

Relational Integrity Constraints Lab (Interactive)

Insert broken rows, switch constraints off, and delete parents to see the damage. Attempt duplicate emails, orphan foreign keys, and negative totals against live UNIQUE, CHECK, and FOREIGN KEY rules, then disable constraints or pick a delete policy to see what integrity costs.

Integrity Constraint Lab: PK · FK · UNIQUE · CHECK

Attempt writes that violate each constraint and watch the engine accept or reject them.

users (PK id · UNIQUE email)
id=1alice@example.com
id=2bob@example.com
orders (FK user_id → users.id · CHECK)
id=101user=1 · $120 · PAID
id=102user=2 · $40 · PENDING
ON DELETE policy for users.id:
Accepted
0
Rejected
0
Orphan rows
0
Bad rows
0
Integrity
HEALTHY

Statement Log

Try an invalid write — then flip Constraints OFF and repeat to see what leaks through.

How It Works Under the Hood

Constraints are declarative contracts enforced by the engine, not application code. A primary key guarantees row uniqueness, a foreign key guarantees every order points at an existing user, UNIQUE blocks duplicate emails, and CHECK encodes business rules like positive totals. Turn them off and the database silently becomes a junk drawer: orphan rows and duplicate identities accumulate with no error raised. ON DELETE policies — RESTRICT, CASCADE, SET NULL — decide whether deleting a parent is blocked, removes dependents, or leaves dangling references.

Core Architectural Principles

  • PRIMARY KEY and UNIQUE enforce entity integrity and business uniqueness at the engine layer, rejecting violating inserts instantly.
  • FOREIGN KEY enforces referential integrity; the ON DELETE clause chooses RESTRICT, CASCADE, or SET NULL semantics when a parent row disappears.
  • CHECK constraints encode domain rules (total > 0), and disabling all constraints exposes silent corruption instead of errors.
Interview Round Script

Argue for constraints as the last line of defense: application validation can be bypassed by bugs or direct SQL, but the engine cannot. Mention that foreign key columns need explicit indexes, or cascading deletes and join performance degrade. Show you choose RESTRICT, CASCADE, or SET NULL deliberately per relationship rather than defaulting blindly.

Key Trade-Offs

Strict constraints guarantee clean data but reject rows your application must handle; lax ones keep writes flowing and corrupt data silently.

Related Curriculum Chapter

Relational Model (Tables, Schemas, Constraints)

Read Full Chapter Blueprint

Explore More Interactive Labs

View All 280 Labs