Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

Part 10 / Stage 3

Building schemas (DDL)

Goal: Turn Part 9's paper design into enforced structure — tables, identity columns, every constraint type, foreign-key actions, live ALTERs, generated columns, enums and domains, and the table flavours that trade durability for speed. Time: ~2.5 hours

What you will learn

  • CREATE DATABASE, CREATE SCHEMA, and what search_path decides
  • CREATE TABLE done properly: types, defaults, GENERATED ALWAYS AS IDENTITY (vs serial)
  • Constraints: PRIMARY KEY, FOREIGN KEY, UNIQUE, CHECK, NOT NULL — named, and tested by breaking them
  • Foreign-key actions: ON DELETE / ON UPDATE — CASCADE, RESTRICT, NO ACTION, SET NULL
  • UNIQUE NULLS NOT DISTINCT
  • ALTER TABLE: evolving a live table
  • Generated columns
  • Enums and domains: custom types with built-in rules
  • Temporary and unlogged tables

This part builds the Part 9 exercise's library inside shopdb — design on paper Monday, DDL on Tuesday.

Topics in this part

Practice

SQL workbench — write and run queries here

Press Run and PostgreSQL loads right in your browser (a one-time download of about 16 MB; after that it works offline). It comes seeded with shopdb, and statements share one session per page — like a psql window. Reset data rebuilds shopdb. Your queries never leave this page. Lessons were captured on PostgreSQL 17; the in-browser server is PostgreSQL 19 (via PGlite), so the rare output detail can differ.

These build structure, so each solution file is re-runnable (it drops its own tables first). The deliberate violations should error — that's the proof.


Exercise 1: The library, in DDL

What to do: Build Part 9's library design for real: authors, books (UNIQUE isbn), the book_authors junction, members (UNIQUE email), loans with named CHECKs (due after loan; return not before loan), and fines (positive amount, CASCADE from loans). Then prove three different constraint classes by violating each once.

Sample output (the three proofs):

ERROR:  insert or update on table "loans" violates foreign key constraint "loans_book_id_fkey"
ERROR:  new row for relation "fines" violates check constraint "fines_amount_check"
ERROR:  duplicate key value violates unique constraint "members_email_key"

💡 Hint: junction = composite PK + two CASCADE FKs; every CHECK gets a CONSTRAINT name.


Show the solution to Exercise 1
-- Exercise 1: The library, in DDL (re-runnable)
DROP TABLE IF EXISTS fines, loans, book_authors, members, books, authors CASCADE;
CREATE TABLE authors (
  author_id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  name      text NOT NULL
);
CREATE TABLE books (
  book_id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  title   text NOT NULL,
  isbn    text UNIQUE
);
CREATE TABLE book_authors (
  book_id   integer REFERENCES books (book_id) ON DELETE CASCADE,
  author_id integer REFERENCES authors (author_id) ON DELETE CASCADE,
  PRIMARY KEY (book_id, author_id)
);
CREATE TABLE members (
  member_id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  name      text NOT NULL,
  email     text NOT NULL UNIQUE
);
CREATE TABLE loans (
  loan_id     integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  book_id     integer NOT NULL REFERENCES books (book_id),
  member_id   integer NOT NULL REFERENCES members (member_id),
  loaned_on   date NOT NULL DEFAULT current_date,
  due_on      date NOT NULL,
  returned_on date,
  CONSTRAINT loans_due_after_loan  CHECK (due_on > loaned_on),
  CONSTRAINT loans_return_sensible CHECK (returned_on IS NULL OR returned_on >= loaned_on)
);
CREATE TABLE fines (
  fine_id   integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  loan_id   integer NOT NULL REFERENCES loans (loan_id) ON DELETE CASCADE,
  amount    numeric(8,2) NOT NULL CHECK (amount > 0)
);
-- One proving violation per rule class (each errors; that is the point):
INSERT INTO loans (book_id, member_id, due_on)
VALUES (1, 1, DATE '2030-01-01');                       -- FK: no such book
INSERT INTO fines (loan_id, amount) VALUES (1, -5);     -- CHECK: amount > 0
INSERT INTO members (name, email) VALUES ('A', '[email protected]');
INSERT INTO members (name, email) VALUES ('B', '[email protected]'); -- UNIQUE email

Exercise 2: Choose the delete policy

What to do: Build playlists and playlist_songs with the FK action that lets deleting a playlist take its entries along; prove it leaves zero orphans. Then contrast: try deleting shopdb's product 1 and explain why that is refused.

Sample output:

 orphaned_entries 
------------------
                0
(1 row)

ERROR:  update or delete on table "products" violates foreign key constraint "order_items_product_id_fkey" on table "order_items"
DETAIL:  Key (product_id)=(1) is still referenced from table "order_items".

💡 Hint: entries are owned parts, so CASCADE; a sold product is referenced history, so the restrictive default is correct.


Show the solution to Exercise 2
-- Exercise 2: Choose the delete policy (re-runnable)
DROP TABLE IF EXISTS playlist_songs, playlists CASCADE;
CREATE TABLE playlists (
  playlist_id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  name        text NOT NULL
);
CREATE TABLE playlist_songs (
  playlist_id integer REFERENCES playlists (playlist_id) ON DELETE CASCADE,
  song        text NOT NULL,
  PRIMARY KEY (playlist_id, song)
);
INSERT INTO playlists (name) VALUES ('Road trip');
INSERT INTO playlist_songs VALUES (1, 'Highway Song'), (1, 'Desert Drive');
-- CASCADE: the entries are owned parts of the playlist.
DELETE FROM playlists WHERE playlist_id = 1;
SELECT count(*) AS orphaned_entries FROM playlist_songs;
-- Versus shopdb's products: order lines REFERENCE products with the
-- restrictive default, so deleting a sold product is refused:
DELETE FROM products WHERE product_id = 1;

Exercise 3: One pending claim each

What to do: A vouchers table where codes are unique and at most one voucher may sit unassigned (NULL code). Prove the second NULL is rejected.

Sample output:

INSERT 0 1
INSERT 0 1
ERROR:  duplicate key value violates unique constraint "vouchers_code_key"
DETAIL:  Key (code)=(null) already exists.

💡 Hint: UNIQUE NULLS NOT DISTINCT (PostgreSQL 15+).


Show the solution to Exercise 3
-- Exercise 3: One pending claim each (re-runnable)
DROP TABLE IF EXISTS vouchers;
CREATE TABLE vouchers (
  voucher_id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  code       text UNIQUE NULLS NOT DISTINCT
);
INSERT INTO vouchers (code) VALUES ('WELCOME10');
INSERT INTO vouchers (code) VALUES (NULL);   -- the one allowed "unassigned"
INSERT INTO vouchers (code) VALUES (NULL);   -- rejected: NULLs now conflict

Exercise 4: The ALTER drill

What to do: On live shopdb tables: add a rating column to suppliers with a 1–5 CHECK; try to add CHECK (stock < 100) to products (predict the outcome first!); add a rule the data actually satisfies; then drop both your constraint and your column, leaving shopdb as found.

Sample output (the refusal):

ERROR:  check constraint "products_small_stock" of relation "products" is violated by some row

💡 Hint: USB-C Cable holds 200 units — existing rows get a vote.


Show the solution to Exercise 4
-- Exercise 4: The ALTER drill
ALTER TABLE suppliers ADD COLUMN rating integer CHECK (rating BETWEEN 1 AND 5);
-- A rule existing rows violate is refused whole:
ALTER TABLE products ADD CONSTRAINT products_small_stock CHECK (stock < 100);
-- A rule that is actually true of the data is accepted:
ALTER TABLE products ADD CONSTRAINT products_stock_sane CHECK (stock <= 500);
-- And constraints are addressable by name:
ALTER TABLE products DROP CONSTRAINT products_stock_sane;
ALTER TABLE suppliers DROP COLUMN rating;

Exercise 5: The self-computing total

What to do: A quote_lines table whose line_total is computed by the database from quantity × unit price. Insert two lines, show the totals, then prove you can't write the total by hand.

Sample output:

 line_id | quantity | unit_price | line_total 
---------+----------+------------+------------
       1 |        4 |      25.00 |     100.00
       2 |        2 |      99.50 |     199.00
(2 rows)

ERROR:  cannot insert a non-DEFAULT value into column "line_total"
DETAIL:  Column "line_total" is a generated column.

💡 Hint: GENERATED ALWAYS AS (quantity * unit_price) STORED.


Show the solution to Exercise 5
-- Exercise 5: The self-computing total (re-runnable)
DROP TABLE IF EXISTS quote_lines;
CREATE TABLE quote_lines (
  line_id    integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  quantity   integer NOT NULL CHECK (quantity > 0),
  unit_price numeric(10,2) NOT NULL,
  line_total numeric(12,2) GENERATED ALWAYS AS (quantity * unit_price) STORED
);
INSERT INTO quote_lines (quantity, unit_price) VALUES (4, 25.00), (2, 99.50);
SELECT * FROM quote_lines;
-- Writing to it is impossible:
INSERT INTO quote_lines (quantity, unit_price, line_total) VALUES (1, 10, 999);

Exercise 6: A PIN-code domain

What to do: Create a pin_code domain (six digits, not starting with 0) and a branches table using it; show a good insert passing and '0001' failing. Then answer in a comment: enum or CHECK for order statuses — and for weekdays?

Sample output (the rejection):

ERROR:  value for domain pin_code violates check constraint "pin_code_check"

💡 Hint: CREATE DOMAIN pin_code AS text CHECK (VALUE ~ '^[1-9][0-9]{5}$'). An evolving vocabulary wants a CHECK or a reference table; only a frozen one earns an enum.

Show the solution to Exercise 6
-- Exercise 6: A PIN-code domain (re-runnable)
DROP TABLE IF EXISTS branches;
DROP DOMAIN IF EXISTS pin_code;
CREATE DOMAIN pin_code AS text CHECK (VALUE ~ '^[1-9][0-9]{5}$');
CREATE TABLE branches (
  branch_id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  city      text NOT NULL,
  pin       pin_code NOT NULL
);
INSERT INTO branches (city, pin) VALUES ('Pune', '411001');
INSERT INTO branches (city, pin) VALUES ('Nowhere', '0001');  -- rejected
-- Judgment call (comment answer): order statuses evolve -> CHECK or a
-- reference table, not an enum; weekdays never change -> enum is fine.

Common mistakes

Mistake What happens Fix
serial in new code Legacy semantics, silent manual ids allowed GENERATED ALWAYS AS IDENTITY
Unnamed constraints ..._check1 in every error, undroppable-by-intent CONSTRAINT meaningful_name CHECK (...)
Constraints never violation-tested Rules that silently don't say what you meant Break each one once, on purpose
CASCADE everywhere One DELETE quietly empties half the schema CASCADE only for owned parts; default to restrict
Enum for a changing vocabulary Every new value is a DDL migration CHECK or a reference table
Business-critical data in UNLOGGED Gone after any crash, absent from replicas UNLOGGED only for regenerable data

Quick recap

  • Schemas are drawers; search_path decides what bare names mean.
  • Identity columns (GENERATED ALWAYS) are the surrogate key; serial is legacy.
  • Name your constraints and prove each one by breaking it once; among FK actions, CASCADE suits owned rows, RESTRICT protects referenced ones, and SET NULL fits optional links.
  • Classic UNIQUE admits many NULLs; NULLS NOT DISTINCT admits one.
  • ALTER evolves live tables and validates existing rows before accepting new rules.
  • Generated columns keep derived data from drifting, a domain states one column rule and reuses it everywhere, and enums are for stable vocabularies only.
  • TEMP dies with the session; UNLOGGED dies with a crash — regenerable data only.

Checklist

Before Part 11, make sure you can:

  • Explain what SHOW search_path output means, line by line.
  • Write a table with identity key, named CHECKs, and a correctly-chosen FK action — from memory.
  • Produce (on purpose) an FK violation, a CHECK violation, and an identity override error.
  • Predict what ADD CONSTRAINT does when existing rows violate it.
  • Choose between enum, CHECK and reference table for a given vocabulary, with reasons.
  • Say which data may live in TEMP or UNLOGGED tables, and which never.

Read more: the official DDL chapter and CREATE TABLE reference.

Search the guide