CHECK: rules a row must keep

Step 1 of 100%

Concept · step 1 of 10

A rule every row must keep

A CHECK is a condition every row must satisfy. A row that breaks it is refused at the moment of the write, by the database, whoever is writing.

  • Column constraint. written on one column, about that column, like CHECK (quantity > 0) or CHECK (status IN ('open', 'paid')).
  • Table constraint. written after the last column, like a column of its own, so it can compare several, like CHECK (discount <= price) in the example.
  • Refused with a name. error 23514 says which constraint broke, so naming it, CONSTRAINT discount_within_price CHECK (...), makes the error say which rule.
CREATE TABLE order_lines (
  quantity INT     NOT NULL CHECK (quantity > 0),
  price    NUMERIC NOT NULL,
  discount NUMERIC NOT NULL,
  CHECK (discount <= price)
);
Every rule you put here is one the application cannot forget, a script cannot skip and a migration cannot quietly break. The steps that follow find the edges of each.
PostgreSQL docs: Constraints ↗

Starting Postgres in your browser

About 5 MB the first time, cached after that.

PostgreSQL running in your browser