Schema Design from Scratch in SQL
Entities → keys → relations → constraints → indexes
Identify entities (customers, orders, lines, products), give each a surrogate key, relate via foreign keys, normalize to 3NF, add NOT NULL/CHECK/UNIQUE, index access paths, seed representative data for EXPLAIN testing. Junction tables carry M2M with composite PK plus relationship attributes. Hierarchies default to adjacency (parent_id) + recursive CTE; paths/nested sets trade write cost for subtree speed.
Entities + surrogates
Customers, orders, lines, products — each with meaningless stable BIGINT IDENTITY.
Relate via FKs
Child holds FK; parent referenced. Explicit ON DELETE per ownership.
Constrain then index
NOT NULL/CHECK/UNIQUE first (correctness), access-path indexes second (speed).
Seed + EXPLAIN
Representative data + plan proof before shipping. M2M via junctions; trees via adjacency+CTE.
1CREATE TABLE orders (2 id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,3 customer_id BIGINT NOT NULL REFERENCES customers(id),4 created_at TIMESTAMPTZ NOT NULL DEFAULT now()5);
| element | role |
|---|---|
| orders | entity + surrogate key |
| customer_id | FK relation |
| created_at | constrained + indexed |
March in order: entities, keys, relations, constraints, indexes. Skipping constraints for app-only validation leaves every job, console and bug as an unguarded writer.
Orders shape
March in order, no shortcuts.
1CREATE TABLE orders (2 id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,3 customer_id BIGINT NOT NULL REFERENCES customers(id),4 created_at TIMESTAMPTZ NOT NULL DEFAULT now()5);
| element | role |
|---|---|
| orders | entity + key |
| customer_id | FK relation |
| created_at | constrained |
M2M + trees default
Junctions for many-many; adjacency for hierarchies.
1CREATE TABLE enrollments (student_id BIGINT REFERENCES students(id), course_id BIGINT REFERENCES courses(id), PRIMARY KEY (student_id, course_id));2-- trees: id, parent_id + WITH RECURSIVE
| model | shape |
|---|---|
| M2M | junction + composite PK |
| trees | adjacency + recursive CTE |
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Take the queries you just visualized and see the data structures that power real databases.