Memra

Data types & constraints

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 *;
NORMAL ~/memra/learn/postgresql/types-and-constraints utf-8 LF