Module 2 · Persistence and the relational data model
2.2 Tables, keys and constraints
Design the first three tables, write them as SQL, and let PostgreSQL reject bad data with primary keys, foreign keys, CHECK constraints and deletion rules.
Starting point
PostgreSQL runs in Docker with two empty databases. The app still uses its in-memory array.
Outcome
A SQL file, migrations/001_create_organisations_buildings_issues.sql, defines three related tables. You apply it by hand, inspect the tables with psql, and watch the database refuse invalid rows.
The problem
Our in-memory issues have a free-text building field: "Cork Apartments". Nothing stops a typo ("Cork Apartmnets"), and nothing connects a building to the company that owns it. Our multi-tenant scenario needs exactly that connection: every issue belongs to a building, every building belongs to an organisation. Later, every authorization decision depends on it, so it must be impossible to store an issue that points at a building that does not exist.
JavaScript validation can check the shape of input, but only the database sees every write, from every process, in a consistent way. So we put the structural rules in the database.
Build it
1. The vocabulary
| Term | Meaning in Caretaker |
|---|---|
| Table | A set of rows with the same columns: organisations, buildings, issues. |
| Primary key | The column that identifies a row: id. Unique and never null. |
| Foreign key | A column that must match a primary key in another table: buildings.organisation_id → organisations.id. |
| Constraint | A rule the database enforces on every write: NOT NULL, UNIQUE, CHECK, foreign keys. |
| Index | A lookup structure that makes searching by a column fast. |
2. Write the schema
Create the folder migrations and this file. The number prefix gives the files a clear order; the next lesson relies on it.
CREATE TABLE organisations ( id integer GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, name text NOT NULL CHECK (length(trim(name)) BETWEEN 2 AND 100), created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now()); CREATE TABLE buildings ( id integer GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, organisation_id integer NOT NULL REFERENCES organisations (id) ON DELETE RESTRICT, name text NOT NULL CHECK (length(trim(name)) BETWEEN 2 AND 100), created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), UNIQUE (organisation_id, name)); CREATE INDEX buildings_organisation_id_idx ON buildings (organisation_id); CREATE TABLE issues ( id integer GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, building_id integer NOT NULL REFERENCES buildings (id) ON DELETE RESTRICT, title text NOT NULL CHECK (length(title) BETWEEN 3 AND 200), description text NOT NULL DEFAULT '', priority text NOT NULL CHECK (priority IN ('low', 'medium', 'high', 'critical')), status text NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'investigating', 'closed')), occurred_at timestamptz NOT NULL, created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now()); CREATE INDEX issues_building_id_idx ON issues (building_id);The choices, one at a time:
integer GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY. PostgreSQL creates a sequence and fillsidwith the next number when we do not supply one.BY DEFAULT(rather thanALWAYS) also lets us insert our own IDs, which we need to seed the fixed scenario: buildings 10, 20, 30, 40 and issue 101.textwithCHECK. PostgreSQL'stexthas no length limit; theCHECKconstraint states the real rule. ACHECKruns on every insert and update.timestamptz. "Timestamp with time zone" stores an exact moment (internally in UTC).DEFAULT now()fills it when the row is created.REFERENCES organisations (id). The foreign key. PostgreSQL refuses a building whoseorganisation_iddoes not exist.ON DELETE RESTRICT. PostgreSQL refuses to delete an organisation that still has buildings, and a building that still has issues. The alternative,ON DELETE CASCADE, would silently delete every child row; for maintenance records we want a deliberate decision instead. Module 3 turns this error into a friendly message.UNIQUE (organisation_id, name). Two buildings in the same organisation cannot share a name, but two organisations can each have a "Main Office".- The indexes. PostgreSQL indexes primary keys automatically but not foreign key columns. "All issues at building 10" and "all buildings of organisation 1" are our most common queries, so we index
building_idandorganisation_id. priorityandstatusastextwith an allowlist. The same values as our JavaScriptPRIORITIES. If the application ever has a bug, the database still holds the line.
3. Apply it by hand
The < sends the file to psql as input. -T tells Docker not to allocate a terminal, which is needed when input comes from a file:
docker compose exec -T db psql -U caretaker -d caretaker < migrations/001_create_organisations_buildings_issues.sql
CREATE TABLE
CREATE TABLE
CREATE INDEX
CREATE TABLE
CREATE INDEX
Each line of output is PostgreSQL confirming one statement.
Run and inspect
\dt lists tables; \d name describes one:
docker compose exec db psql -U caretaker caretaker, then paste the SQL.\dt\d buildings
List of tables
Schema | Name | Type | Owner
--------+---------------+-------+-----------
public | buildings | table | caretaker
public | issues | table | caretaker
public | organisations | table | caretaker
(3 rows)
Table "public.buildings"
Column | Type | Collation | Nullable | Default
-----------------+--------------------------+-----------+----------+----------------------------------
id | integer | | not null | generated by default as identity
organisation_id | integer | | not null |
name | text | | not null |
created_at | timestamp with time zone | | not null | now()
updated_at | timestamp with time zone | | not null | now()
Indexes:
"buildings_pkey" PRIMARY KEY, btree (id)
"buildings_organisation_id_idx" btree (organisation_id)
"buildings_organisation_id_name_key" UNIQUE CONSTRAINT, btree (organisation_id, name)
Check constraints:
"buildings_name_check" CHECK (length(TRIM(BOTH FROM name)) >= 2 AND length(TRIM(BOTH FROM name)) <= 100)
Foreign-key constraints:
"buildings_organisation_id_fkey" FOREIGN KEY (organisation_id) REFERENCES organisations(id) ON DELETE RESTRICT
Referenced by:
TABLE "issues" CONSTRAINT "issues_building_id_fkey" FOREIGN KEY (building_id) REFERENCES buildings(id) ON DELETE RESTRICTRead the \d buildings output from the bottom: the indexes, the check constraint, the foreign key (buildings_organisation_id_fkey), and "Referenced by", which shows that issues points at buildings.
Insert an organisation and a building, letting the identity columns choose IDs, and read them back with a join:
docker compose exec db psql -U caretaker caretaker, then paste the SQL.INSERT INTO organisations (name) VALUES ('Liffey Estates') RETURNING id, name, created_at;INSERT INTO buildings (organisation_id, name) VALUES (1, 'Dublin Offices') RETURNING *;SELECT s.id, s.name AS building, o.name AS organisationFROM buildings sJOIN organisations o ON o.id = s.organisation_id;
id | name | created_at
----+----------------+-------------------------------
1 | Liffey Estates | 2026-11-28 14:39:23.670525+00
(1 row)
INSERT 0 1
id | organisation_id | name | created_at | updated_at
----+-----------------+----------------+------------------------------+------------------------------
1 | 1 | Dublin Offices | 2026-11-28 14:39:23.67228+00 | 2026-11-28 14:39:23.67228+00
(1 row)
INSERT 0 1
id | building | organisation
----+----------------+----------------
1 | Dublin Offices | Liffey Estates
(1 row)RETURNINGmakes anINSERTreturn the row it created, including generated values. Our app will use this to learn the new issue's ID.JOIN ... ONcombines rows from two tables where the condition is true.sandoare short aliases.
Experiment
Each block below wraps its statements in a transaction (BEGIN) and ends with a statement that PostgreSQL must refuse. The error aborts the transaction, so nothing in the block is kept. When you type these yourself, run ROLLBACK; after the error to leave the aborted transaction.
docker compose exec db psql -U caretaker caretaker, then paste the SQL.BEGIN;INSERT INTO buildings (organisation_id, name) VALUES (999, 'Ghost Building');
BEGIN
ERROR: insert or update on table "buildings" violates foreign key constraint "buildings_organisation_id_fkey"
DETAIL: Key (organisation_id)=(999) is not present in table "organisations".extreme?docker compose exec db psql -U caretaker caretaker, then paste the SQL.BEGIN;INSERT INTO issues (building_id, title, priority, occurred_at)VALUES (1, 'Too much drama', 'extreme', now());
BEGIN
ERROR: new row for relation "issues" violates check constraint "issues_priority_check"
DETAIL: Failing row contains (1, 1, Too much drama, , extreme, open, 2026-11-28 14:39:23.867773+00, 2026-11-28 14:39:23.867773+00, 2026-11-28 14:39:23.867773+00).docker compose exec db psql -U caretaker caretaker, then paste the SQL.BEGIN;DELETE FROM organisations WHERE id = 1;
BEGIN
ERROR: update or delete on table "organisations" violates RESTRICT setting of foreign key constraint "buildings_organisation_id_fkey" on table "buildings"
DETAIL: Key (id)=(1) is referenced from table "buildings".Reveal What these errors give us
Each error has a SQLSTATE code and names the constraint: 23503 foreign key violation (the parent row does not exist), 23514 check violation, and 23001 restrict violation (children still point at the row). In psql, \set VERBOSITY verbose shows the codes. In Module 2.6 and Module 3 our app catches these codes and turns them into form messages, instead of a 500 page. The rules hold even if a future script, a second app or a bug in our JavaScript tries to write bad data.
Checkpoint
docker compose exec db psql -U caretaker caretaker, then paste the SQL.SELECT count(*) AS organisations FROM organisations;SELECT count(*) AS buildings FROM buildings;
organisations
---------------
1
(1 row)
buildings
-----------
1
(1 row)You should have exactly one organisation and one building: the failed blocks left nothing behind.
git add -A
git commit -m "Add the first schema: organisations, buildings, maintenance issues"
[main 9524113] Add the first schema: organisations, buildings, maintenance issues
1 file changed, 31 insertions(+)
create mode 100644 migrations/001_create_organisations_buildings_issues.sql
Symptom ERROR: relation "organisations" already exists
You applied the file twice. That is precisely the problem the next lesson solves. For now, ignore it, or reset with docker compose down -v && docker compose up -d --wait and apply once.
Symptom the input device is not a TTY
You used < without -T. Add -T after exec.
Recap and next step
Tables hold rows; primary keys identify them; foreign keys link them; CHECK, NOT NULL and UNIQUE describe valid data; ON DELETE RESTRICT makes deletion a deliberate act. PostgreSQL enforced all of it while we watched.
But we applied the schema by typing a command. How will a teammate, the test database, or a server next year know which SQL files have already run? Next we write a small migration runner.
Open the checkpoint files for lesson 2.2 (separate page; only files from this lesson and earlier)