Memra

Data types & constraints

◈ 2 cards

Let the database enforce your rules.

The database guards your data

A good schema makes bad data impossible. Postgres enforces constraints at write time:

  • PRIMARY KEY — unique, not-null row identifier
  • REFERENCES (foreign key) — value must exist in another table
  • UNIQUE — no duplicates (e.g. customers.email)
  • NOT NULL — value required
  • CHECK (...) — any boolean rule

Pick types deliberately: int, numeric(6,2) for money (never float!), text, date, boolean. Create a small table with a CHECK and watch Postgres reject a bad row:

CREATE TABLE ratings (
  book_id int NOT NULL,
  stars   int NOT NULL CHECK (stars BETWEEN 1 AND 5)
);
INSERT INTO ratings VALUES (1, 5) RETURNING *;
constraintrefusesin the bookshopPRIMARY KEYa duplicate or NULL idbooks.idREFERENCESan author_id with no authorbooks.author_idUNIQUEa second row with thatemailcustomers.emailNOT NULLa missing valuebooks.titleCHECKstars outside 1–5ratings.starsBad data is refused at write time, not found later.
A constraint is a rule you only have to write once. Every row here is a class of bad data that can never reach the table, no matter which application, script or console does the writing.
NORMAL ~/memra/learn/postgresql/types-and-constraints utf-8 LF