Code of the Day
AdvancedDesign & performance

Constraints and keys

Let the database enforce your rules — primary keys, foreign keys, NOT NULL, UNIQUE, CHECK.

SQLAdvanced9 min read
By the end of this lesson you will be able to:
  • Declare primary and foreign keys
  • Enforce rules with NOT NULL, UNIQUE, and CHECK
  • See a constraint reject bad data

A is a rule the database enforces on every insert and update. Constraints keep data valid no matter what code touches it — far safer than hoping every application remembers the rule.

The main constraints

  • — uniquely identifies each row; implies unique + not null.
  • FOREIGN KEY — a value must exist in another table's key (referential integrity).
  • NOT NULL — the column must have a value.
  • UNIQUE — no two rows share the value (e.g. an email).
  • CHECK — a custom condition must hold (e.g. price >= 0).

See one reject bad data

Create a table with a UNIQUE email and a CHECK, then try to violate them — the database refuses the bad row:

SQL — editable, runs in your browser

The second insert fails the UNIQUE constraint, so it's rejected. Try changing balance to a negative number, or removing the email, to trip the other rules.

Constraints are validation you can't forget to run — they live with the data, not in one app. This is "say what you mean precisely" (the very first fundamentals lesson) enforced by the database itself.

Where to go next

Constraints keep data correct; indexes keep queries fast. Next.

Finished reading? Mark it complete to track your progress.

On this page