Data types & constraints
◈ 2 cardsLet 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 identifierREFERENCES(foreign key) — value must exist in another tableUNIQUE— no duplicates (e.g.customers.email)NOT NULL— value requiredCHECK (...)— 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 *;