Constraints

Rules on a table's columns that the database enforces, so invalid data can't be saved.

What is it?

Primary and foreign keys are two kinds of a broader idea: a constraint, a rule on a column (or set of columns) that no row may break. Beyond keys, the common ones are:

- NOT NULL: the column can never be empty. - UNIQUE: no two rows may share the same value. - DEFAULT: fill in a value automatically when none is given. - CHECK: a custom condition the value must meet, like "price must be greater than zero."

The point is the same for all of them: instead of trusting every piece of app code, forever, to validate, the database enforces the rule itself, no matter what code writes to it.

Explain like I'm 10

Constraints are like the slots on a vending machine tray. A can won't fit sideways, not because someone checked, but because the slot is shaped that way. App-level validation is more like a sign asking people to load cans upright: helpful, but easy to ignore.

Examples

The four common non-key constraints

CREATE TABLE products (
  id SERIAL PRIMARY KEY,
  sku TEXT UNIQUE NOT NULL,
  name TEXT NOT NULL,
  price_cents INTEGER NOT NULL CHECK (price_cents > 0),
  in_stock BOOLEAN NOT NULL DEFAULT true
);

Four rules the database always enforces: no two products share a sku, name and price_cents can't be empty, price_cents must be positive, and in_stock defaults to true when not given.

What happens when a constraint is violated

INSERT INTO products (sku, name, price_cents)
VALUES ('SKU-1', 'Desk Lamp', -500);
-- ERROR: new row violates check constraint "products_price_cents_check"

The insert never happens. The database rejects the whole statement as soon as any constraint fails, instead of saving a partly valid row.

How it works

Constraints are checked whenever a row is inserted or updated, before the change is committed. If any constraint fails, the whole statement is rejected and nothing is written. There's no "half-valid" row.

That makes constraints the last line of defense. Even if app validation has a bug, gets bypassed, or another app (or a future developer) writes to the table without knowing the rules, the database still refuses invalid data.

Why does it exist?

If only app code validates data, every place that writes to a table (every service, script, and future feature) must remember and correctly repeat the same rules. Constraints put the rule in the one place all writers pass through: the database, where it can't be forgotten or bypassed.

When to use it

Add a constraint for any rule that must always hold: a price that's never negative, an email that must be unique, a status that's never blank. Keep app-level validation too (for friendlier, earlier error messages), but the constraint is what guarantees the rule.

When not to use it

Constraints can't handle validation that needs context the database doesn't have, like "this discount code only works for accounts created in the last 30 days." They also can't give friendly, specific form error messages. Put that logic in app-level validation.

Common mistakes

  • Validating only in app code and assuming that's enough, when another script, migration, or service writing to the table can bypass it.

  • Adding a UNIQUE constraint to a table that already has duplicates. It fails until you clean them up.

  • Forgetting that a failed constraint rejects the whole statement, not just the bad column, so the other changes in that INSERT or UPDATE are rejected too.

Practice exercises

  1. Easy:

    Write a CREATE TABLE for a coupons table whose code column must be unique and not null.

  2. Medium:

    Add a CHECK constraint to a reservations table so party_size is always greater than 0.

  3. Hard:

    Explain why app-only validation of 'email must be unique' can still let duplicate emails in, and how a UNIQUE constraint prevents that whatever the app does.

Interview questions

What is a database constraint?

A rule on a column or set of columns that the database enforces, rejecting any row that breaks it.

What's the difference between NOT NULL and CHECK?

NOT NULL only requires a value. CHECK requires the value to meet a custom condition, like being greater than zero.

Why add a database constraint if the application already validates the same rule?

App validation can be bypassed, buggy, or missing in other code that writes to the same table. The constraint guarantees the rule holds whatever writes to the database.