skipnothing/SQL

Constraints

An order arrives carrying amount = -5, and a plain orders table stores it without complaint. Add one rule to that column and the same write bounces back rejected, the bad row never lands.

  • ▸A NULL amount slips past CHECK (amount > 0), because a comparison with nothing is unknown, never false.
  • ▸An email column marked UNIQUE still takes many rows whose value is NULL: two missing values never duplicate.
  • ▸Deleting one user can delete orders you never named: ON DELETE CASCADE propagates down the foreign key.
BUILDS ON
01

A rule the table enforces

The orders table has taken every row handed to it so far. A refund glitch sends one more: INSERT INTO orders (id, user_id, amount) VALUES (109, 2, -5). Against a bare table the row lands, a negative amount and all, and the count comes back INSERT 0 1. Nothing in the table knew the number was wrong.

Now attach a rule to the amount column, every row's amount must be greater than zero, and run the exact same write. This time the database refuses it: no row is added, no count is returned, just an error naming the rule that was broken. The table itself, not the application, did the refusing.

That refusal is the whole idea. A rule declared on the table is checked on every write, by every writer, for as long as the rule stands. The data can no longer drift into a shape the rule forbids.

WRITE THE RULE THE TABLE ENFORCES

Keep going, sign up to unlock the rest

4 more parts in this topic, plus 30+ more topics in SQL.

Sign up, it's freeSee the full SQL
Writes, Constraints & Transactions0/4#24 INSERT, UPDATE, DELETE
#26 Transactions & ACID