Skip to the workspace
Pebellslearn by building
Object Model  ›  Capstone Project

Constraints and NULL

Constraints 12 minConstraints make the database refuse bad rows, and NULL means unknown, which follows three-valued logic and slips past CHECK and UNIQUE.

postgresql dba / Constraints and NULL

Explore each scene at your own pace.

01 · The rule

The rule

Constraints and NULL

A bug in Pedal's app once created a rental that ended before it started, and another for bike id 0, which does not exist. Code will always have bugs. Constraints are rules the database itself enforces, so bad rows are refused no matter which program sends them.

The rule

Let the database refuse bad data; treat NULL as "unknown", not zero.

PostgreSQL's constraints:

  • NOT NULL: the column must have a value.
  • UNIQUE: no two rows share this value (or combination).
  • PRIMARY KEY: UNIQUE plus NOT NULL; the row's identity. One per table.
  • FOREIGN KEY (REFERENCES): the value must exist in another table.
  • CHECK: any true-or-false rule on the row.
  • EXCLUDE: no two rows may overlap by some operator, such as two bookings of one bike at the same time.
CREATE TABLE rentals (
  rental_id  bigint PRIMARY KEY,
  member_id  bigint NOT NULL REFERENCES members,
  bike_id    bigint NOT NULL REFERENCES bikes,
  started_at timestamptz NOT NULL,
  ended_at   timestamptz,
  CHECK (ended_at IS NULL OR ended_at > started_at)
);

ended_at may be NULL, meaning "not known yet": the ride is still going. NULL is not zero and not an empty string, and it follows three-valued logic: any comparison with NULL gives unknown, not true or false.

  • ended_at = NULL is never true. Use ended_at IS NULL.
  • WHERE keeps only rows where the condition is true, so unknown rows drop out.
  • A CHECK passes unless the result is false, so NULL slips through a check. That is why the check above spells out the NULL case.
  • UNIQUE allows many NULLs by default, because two unknowns are not known to be equal. PostgreSQL 15 added UNIQUE NULLS NOT DISTINCT to forbid that.
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.