Explain it simply
Explain it simply
Over the next three lessons you will build a database for a small bookshop. Part 1 writes no reports yet; it builds the structure that answers "what does the shop need to remember?". Picture four record books: authors, books, customers and orders.
The order book does not repeat the customer's name and the book's title on every line. It just writes "customer 1, book 102". A foreign key is the rule that tells the database to guard those numbers: each one must belong to a customer and a book that really exist.
Problem → Why → Solution
The problem: a script in the wrong order with no guard rails
The first draft creates the Orders table first. PostgreSQL stops at once with relation "books" does not exist, because a foreign key cannot point at a table that is not there yet. Removing every foreign key makes the script run, but it lets in a worse problem.
With no constraints, an order for BookID 999 (a book that does not exist), an order with Quantity -2, and a customer with no name all go in without complaint. In Part 3, when you report how much each customer spent, the join silently drops the orphan order and the totals are wrong.
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
BookID INT REFERENCES Books(BookID), -- Books does not exist yet
Quantity INT
);
-- ERROR: relation "books" does not exist
-- "Fix": drop the foreign key and every other rule
CREATE TABLE Orders (OrderID INT, BookID INT, Quantity INT);
INSERT INTO Orders VALUES (1, 999, -2); -- accepted: no such book, negative qtyWhy constraints matter
Even if the application validates input, scripts, import jobs and an admin's hand-written SQL never pass through that code. Constraints inside the database check every row, no matter where it comes from. Keeping those constraints means creating the tables in the order their relationships require.
Core concept: entities, relationships, constraints
Do not start table design from column names. Start from "what things exist and how are they related?". The bookstore has four entities. One author can write many books (one-to-many). One customer can place many orders, and one book can appear in many orders, so Orders is the table that links Customers and Books. The foreign key column always lives on the "many" side.
Bookstore schema
----------------
Authors (AuthorID PK) Customers (CustomerID PK)
| 1 | 1
| |
| many | many
Books (BookID PK, 1 ------ many Orders (OrderID PK,
AuthorID FK) CustomerID FK,
BookID FK)1. A primary key identifies one row
AuthorID INT PRIMARY KEY combines NOT NULL and UNIQUE, and PostgreSQL builds an index for it automatically. This project assigns ids by hand to keep the sample data readable; a real app usually lets the database generate them with GENERATED ALWAYS AS IDENTITY.
2. A foreign key accepts only existing parents
With FOREIGN KEY (BookID) REFERENCES Books(BookID), every BookID inserted into Orders must already exist in Books, and by default PostgreSQL also refuses to delete a book that still has orders. The creation order is therefore Authors, Books, Customers, Orders, and data is loaded in the same order.
3. NOT NULL and DEFAULT state what is required
A book without a title or an order without a customer makes no sense, so those columns are NOT NULL. Stock defaults to 0 and OrderDate defaults to today's date when omitted. Country and City may legitimately be unknown, so they allow NULL.
4. CHECK and UNIQUE guard business rules
CHECK (Quantity > 0) rejects zero or negative orders and CHECK (Stock >= 0) rejects negative stock. Email UNIQUE stops two customers from sharing an address, but note that PostgreSQL's UNIQUE is case-sensitive and allows many NULLs.
- Sketch entities and relationships
- Put the FK on the many side
- Give every column its rules
- Create and load parents first
- Verify with row counts
When a foreign key error appears, first ask: does the parent row exist yet?
General pattern
CREATE TABLE parent (
parent_id INT PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
CREATE TABLE child (
child_id INT PRIMARY KEY,
parent_id INT NOT NULL REFERENCES parent(parent_id),
amount INT NOT NULL CHECK (amount > 0),
code VARCHAR(50) UNIQUE
);
INSERT INTO parent VALUES (...); -- parents first
INSERT INTO child VALUES (...); -- then childrenA foreign key can be written inline with REFERENCES next to the column, or at the end of the table as FOREIGN KEY (...) REFERENCES .... Either way, the parent table and parent rows must exist first.
The Bookstore schema and sample data
The script below creates the four tables and loads 3 authors, 5 books, 3 customers and 4 orders. Compared with the first design it adds CHECK constraints, NOT NULL on the Orders foreign key columns, and a DEFAULT for OrderDate. Parts 2 and 3 run on exactly this data, so note who bought what. The final query checks how many rows landed in each table.
CREATE TABLE Authors (
AuthorID INT PRIMARY KEY,
AuthorName VARCHAR(100) NOT NULL,
Country VARCHAR(50)
);
CREATE TABLE Books (
BookID INT PRIMARY KEY,
Title VARCHAR(150) NOT NULL,
AuthorID INT NOT NULL,
Price DECIMAL(10,2) NOT NULL CHECK (Price >= 0),
Stock INT NOT NULL DEFAULT 0 CHECK (Stock >= 0),
FOREIGN KEY (AuthorID) REFERENCES Authors(AuthorID)
);
CREATE TABLE Customers (
CustomerID INT PRIMARY KEY,
CustomerName VARCHAR(100) NOT NULL,
Email VARCHAR(100) UNIQUE,
City VARCHAR(50)
);
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
CustomerID INT NOT NULL,
BookID INT NOT NULL,
Quantity INT NOT NULL CHECK (Quantity > 0),
OrderDate DATE NOT NULL DEFAULT CURRENT_DATE,
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID),
FOREIGN KEY (BookID) REFERENCES Books(BookID)
);
INSERT INTO Authors VALUES
(1, 'Aung Aung', 'Myanmar'),
(2, 'J.K Rowling', 'UK'),
(3, 'Haruki Murakami', 'Japan');
INSERT INTO Books (BookID, Title, AuthorID, Price, Stock) VALUES
(101, 'Myanmar Sarpay', 1, 5000, 20),
(102, 'Harry Potter', 2, 15000, 10),
(103, 'Norwegian Wood', 3, 12000, 8),
(104, 'Kafka on the Shore', 3, 13000, 5),
(105, 'Fantastic Beasts', 2, 14000, 0);
INSERT INTO Customers VALUES
(1, 'Su Su', 'susu@mail.com', 'Yangon'),
(2, 'Ko Ko', 'koko@mail.com', 'Mandalay'),
(3, 'Hla Hla', 'hlahla@mail.com', 'Yangon');
INSERT INTO Orders VALUES
(1, 1, 102, 2, '2026-01-05'),
(2, 2, 101, 1, '2026-01-10'),
(3, 3, 103, 3, '2026-01-12'),
(4, 1, 104, 1, '2026-02-01');
-- Check: every table received its sample rows
SELECT 'Authors' AS table_name, COUNT(*) AS row_count FROM Authors
UNION ALL SELECT 'Books', COUNT(*) FROM Books
UNION ALL SELECT 'Customers', COUNT(*) FROM Customers
UNION ALL SELECT 'Orders', COUNT(*) FROM Orders;Code breakdown
- Primary key
AuthorID INT PRIMARY KEY,Each author is identified by one number; PostgreSQL rejects a duplicate or NULL id.
- Foreign key to the parent
FOREIGN KEY (AuthorID) REFERENCES Authors(AuthorID)Every AuthorID in Books must exist in Authors, which is why Authors is created and filled first.
- Business rules as CHECK
Quantity INT NOT NULL CHECK (Quantity > 0),The database itself refuses an order with zero or negative quantity, even if application code forgets to check.
- One email per customer
Email VARCHAR(100) UNIQUE,Stops two customers from sharing an email and automatically creates an index that speeds up lookups by email.
- Verify the load
UNION ALL SELECT 'Books', COUNT(*) FROM BooksUNION ALL stacks each table's COUNT(*) into one result. Anything other than 3, 5, 3, 4 means an INSERT did not succeed.
table_name | row_count
------------+-----------
Authors | 3
Books | 5
Customers | 3
Orders | 4
(4 rows)PostgreSQL folds identifiers to lowercase
The script writes Authors and AuthorID, but PostgreSQL folds unquoted names to lowercase: the real table is authors and the column is authorid. That is why result headers in Parts 2 and 3 show lowercase names such as authorname and totalspent. As long as you never quote, AuthorID, authorid and AUTHORID all work.
Trouble starts with double quotes. SELECT "AuthorID" FROM Authors; fails with column "AuthorID" does not exist, because a quoted name is matched exactly. Some ORMs create tables with quoted names, and then every query has to quote them. For new PostgreSQL projects, snake_case (author_id) is the simplest choice.
| Database | What differs |
|---|---|
| PostgreSQL | Folds unquoted names to lowercase; always enforces CHECK |
| MySQL | Table-name case sensitivity depends on OS and settings; CHECK was ignored before 8.0.16 |
| SQLite | Foreign keys are enforced only after PRAGMA foreign_keys = ON |
In real projects
In real projects
Real teams do not run a CREATE TABLE script by hand once and forget about it. They keep numbered files such as 001_create_authors.sql and 002_create_books.sql in Git and apply them in order on every environment with a migration tool like Flyway, Liquibase, Prisma Migrate or Django migrations. A new developer can then build an empty database with the same structure as production using a single command.
Sample data lives in a separate seed script that tests and demos reuse, and this lesson's INSERT statements are exactly that kind of script. Because the seed ids are fixed, tests can confidently assert facts like "customer 1 spent 43000". Migrations that add constraints to a table already full of data also fail when old rows break the new rule, so teams clean the data first.
Common mistakes
Common mistakes
Inserting an id that does not exist in the parent
INSERT INTO Orders VALUES (5, 1, 999, 1, '2026-02-03'); fails with violates foreign key constraint "orders_bookid_fkey". The constraint name in the message tells you which column is at fault. Insert the parent row first, or fix the id.
Omitting the column list in INSERT ... VALUES
INSERT INTO Customers VALUES (...) assigns values by the table's column order. Add a column later and the script can break; swap two columns of the same type and wrong data goes in without any error. Listing the columns, as the Books insert does, is safer.
Trusting UNIQUE to fully protect emails
Even with Email UNIQUE, 'SUSU@mail.com' is accepted because it differs from 'susu@mail.com', and any number of NULL emails can go in. For case-insensitive uniqueness use a unique index on lower(Email), and add NOT NULL if an email is mandatory.
Mini challenge
Add a Publishers table and link it to Books
Every book has a publisher. Create a new Publishers table, then use ALTER TABLE to add a foreign key column to the existing Books table. Some books' publishers are not known yet, so the column must allow NULL.
- Create Publishers(PublisherID PRIMARY KEY, PublisherName NOT NULL UNIQUE)
- Insert Sarpay Beikman, Bloomsbury and Vintage
- Add a PublisherID foreign key column to Books
- Set 101 to 1, 102 and 105 to 2, 103 to 3, and leave 104 NULL
- List every book with its publisher name using LEFT JOIN, ordered by BookID
-- The four Bookstore tables and their data already exist.
CREATE TABLE Publishers (
-- TODO: PublisherID primary key, PublisherName required and unique
);
-- TODO: insert (1, 'Sarpay Beikman'), (2, 'Bloomsbury'), (3, 'Vintage')
-- TODO: ALTER TABLE Books ... add a nullable PublisherID that references Publishers
-- TODO: UPDATE Books so 101 -> 1, 102 and 105 -> 2, 103 -> 3 (104 stays NULL)
-- TODO: SELECT each Title with its PublisherName (keep books without one)Expected: Five rows: Myanmar Sarpay - Sarpay Beikman, Harry Potter - Bloomsbury, Norwegian Wood - Vintage, Kafka on the Shore - (empty), Fantastic Beasts - Bloomsbury.
Show hint
ALTER TABLE Books ADD COLUMN PublisherID INT REFERENCES Publishers(PublisherID); adds the column and its foreign key in one statement. With INNER JOIN, Kafka on the Shore would vanish from the result.
Show solution
CREATE TABLE Publishers (
PublisherID INT PRIMARY KEY,
PublisherName VARCHAR(100) NOT NULL UNIQUE
);
INSERT INTO Publishers (PublisherID, PublisherName) VALUES
(1, 'Sarpay Beikman'),
(2, 'Bloomsbury'),
(3, 'Vintage');
ALTER TABLE Books
ADD COLUMN PublisherID INT REFERENCES Publishers(PublisherID);
UPDATE Books SET PublisherID = 1 WHERE BookID = 101;
UPDATE Books SET PublisherID = 2 WHERE BookID IN (102, 105);
UPDATE Books SET PublisherID = 3 WHERE BookID = 103;
SELECT b.Title, p.PublisherName
FROM Books AS b
LEFT JOIN Publishers AS p ON p.PublisherID = b.PublisherID
ORDER BY b.BookID;Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Start design from entities and relationships; the foreign key goes on the many side
- Create parent tables first and insert parent rows first
- NOT NULL, DEFAULT, CHECK and UNIQUE enforce business rules inside the database
- PostgreSQL lowercases unquoted names, so do not mix in quoted identifiers
- Check every load with a row count
PostgreSQL SQL Tutorial — PostgreSQL Global Development Group