SQL course · Module 8: Database design · Lesson 28 of 40
Quick answer: Database design starts with an ER diagram (entity-relationship diagram): a drawing of the things you store (entities, which become tables), their details (attributes, which become columns) and how they connect (relationships, which become foreign keys). Each relationship has a cardinality: one-to-one, one-to-many or many-to-many. A one-to-many relationship becomes a foreign key on the “many” side, and a many-to-many relationship needs a third table, called a junction table, with two foreign keys.
In this lesson you will learn:
- what entities, attributes and relationships are, using the shop database
- how to read one-to-one, one-to-many and many-to-many in crow’s foot notation
- the difference between primary, foreign, candidate, natural and surrogate keys
- how to turn an ER model into CREATE TABLE statements
- the real foreign key errors you meet when you get the design wrong
Before you start: Lesson 1, What Is a Relational Database? Tables, Rows, Columns and Keys and Lesson 16, SQL CREATE TABLE: Data Types and Constraints. Module 7 ended with Lesson 27, SQL Window Functions: 15 Practice Problems with Answers.
We ran every example on PostgreSQL 16.15 with the shop database and checked the current PostgreSQL 18 manual. Everything here works on newer versions too. This lesson creates three small practice tables and drops them at the end, so the four shop tables stay unchanged.
Table of Contents
Database design: from words to an ER model
Design starts with the business in plain words. For our shop:
- A customer signs up and can place orders.
- An order belongs to one customer and contains one or more products.
- A product can appear in many orders.
The nouns are the entities: customer, order, product. The details of each noun are its attributes: a customer has a name, an email and a city. The verbs are the relationships: a customer places orders, an order contains products.
An ER model draws this as boxes and lines. Peter Chen published the entity-relationship model in 1976 (Chen’s paper), and crow’s foot notation was invented by Gordon Everest (University of Regina: Crow’s Foot Notation).
Read the shop ER model from the database
You do not have to guess the design of an existing database. PostgreSQL keeps every constraint in the system table pg_constraint; this query lists the keys (p = primary key, u = unique, f = foreign key):
SELECT conrelid::regclass AS table_name,
pg_get_constraintdef(oid) AS key_definition
FROM pg_constraint
WHERE connamespace = 'public'::regnamespace
AND contype IN ('p', 'u', 'f')
ORDER BY conrelid::regclass::text, contype DESC, conname;
table_name | key_definition
-------------+----------------------------------------------------
customers | UNIQUE (email)
customers | PRIMARY KEY (id)
order_items | PRIMARY KEY (order_id, product_id)
order_items | FOREIGN KEY (order_id) REFERENCES orders(id)
order_items | FOREIGN KEY (product_id) REFERENCES products(id)
orders | PRIMARY KEY (id)
orders | FOREIGN KEY (customer_id) REFERENCES customers(id)
products | PRIMARY KEY (id)
(8 rows)
These eight lines are the skeleton of the ER model: four primary keys, three foreign keys and one unique rule. Each FOREIGN KEY is one line in the diagram.

Relationships and cardinality
Cardinality answers “how many?” on each end of a relationship. Crow’s foot notation draws it with two symbols at each end of a line: a ring means zero, a dash means one, and the crow’s foot (three short lines) means many. The symbol touching the box is the maximum; the symbol just before it, further along the line, is the minimum (Practical Databases: ERD notations).
| symbols (minimum, then maximum next to the box) | meaning | shop example |
|---|---|---|
| dash, dash | exactly one | each order has exactly one customer |
| ring, dash | zero or one | a customer has zero or one profile |
| ring, crow’s foot | zero or many | a customer has zero or many orders |
| dash, crow’s foot | one or many | an order has one or many order lines |
One-to-many: customers and orders
orders.customer_id is a foreign key to customers(id), and it is NOT NULL, so every order points to exactly one customer. How many orders can one customer have? Let the data answer, with a LEFT JOIN so that customers without orders count as 0 (Lesson 13):
SELECT MIN(n) AS min_orders, MAX(n) AS max_orders
FROM (SELECT c.id, COUNT(o.id) AS n
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id) AS per_customer;
min_orders | max_orders
------------+------------
0 | 4
(1 row)
Omar Haddad has 0 orders and Ayesha Malik has 4, so the customer side reads “zero or many”. The rule: in a one-to-many relationship, the foreign key goes on the “many” side. The order stores its customer; the customer does not store a list of orders.
Many-to-many: orders and products
One order can contain many products, and one product can appear in many orders. A column cannot hold a list of values in a good design (Lesson 29 explains why), so the shop uses a third table. order_items is a junction table: each row joins one order to one product and adds the facts about that pair (quantity and unit price).
SELECT 'products per order' AS side, MIN(n) AS min, MAX(n) AS max
FROM (SELECT o.id, COUNT(oi.product_id) AS n
FROM orders o LEFT JOIN order_items oi ON oi.order_id = o.id
GROUP BY o.id) AS t
UNION ALL
SELECT 'orders per product', MIN(n), MAX(n)
FROM (SELECT p.id, COUNT(oi.order_id) AS n
FROM products p LEFT JOIN order_items oi ON oi.product_id = p.id
GROUP BY p.id) AS t;
side | min | max
--------------------+-----+-----
products per order | 1 | 3
orders per product | 0 | 6
(2 rows)
Every order has 1 to 3 products, and a product sits in 0 to 6 orders (the Ergonomic Chair was never ordered). A many-to-many relationship is really two one-to-many relationships that meet in order_items. The PostgreSQL manual uses almost the same products, orders and order_items example to explain this (PostgreSQL docs: Constraints).
One-to-one: a customer profile
The shop has no one-to-one relationship yet, so we add one: optional details in a separate table. The trick is that the foreign key is also the primary key, so each customer can have at most one row.
CREATE TABLE customer_profiles (
customer_id integer PRIMARY KEY REFERENCES customers (id),
birthday date,
newsletter boolean NOT NULL DEFAULT false
);
INSERT INTO customer_profiles (customer_id, newsletter) VALUES (1, true);
INSERT INTO customer_profiles (customer_id) VALUES (1);
CREATE TABLE
INSERT 0 1
ERROR: duplicate key value violates unique constraint "customer_profiles_pkey"
DETAIL: Key (customer_id)=(1) already exists.
The second profile for customer 1 is rejected. Without PRIMARY KEY (or UNIQUE) on customer_id, this would be one-to-many by accident.
Keys: primary, candidate, natural and surrogate
- A candidate key is a column, or a set of columns, that could identify every row: unique, never NULL, and with no extra column you could drop.
- The primary key is the one candidate key you choose. A table has at most one.
- A foreign key is a column that points to the primary key or a unique column of another table (or of the same table).
- A natural key is a real-world value, like an email address.
- A surrogate key is a made-up number with no meaning, like
customers.id.
Is email a candidate key for customers? Count it:
SELECT COUNT(*) AS customers,
COUNT(DISTINCT id) AS distinct_ids,
COUNT(email) AS emails,
COUNT(DISTINCT email) AS distinct_emails
FROM customers;
customers | distinct_ids | emails | distinct_emails
-----------+--------------+--------+-----------------
10 | 10 | 9 | 9
(1 row)
The 9 emails are all different, and the UNIQUE rule keeps it that way. But Emma Clarke has no email, so email cannot identify all 10 rows. PostgreSQL agrees when we try to make it required:
ALTER TABLE customers ALTER COLUMN email SET NOT NULL;
ERROR: column "email" of relation "customers" contains null values
This is why the shop uses a surrogate key. Natural keys can be missing, can change (people change email addresses) and can be long. A surrogate id is short, stable and never NULL. Keep the natural value too, with a UNIQUE rule, so duplicates are still blocked.
order_items shows the other choice: its primary key (order_id, product_id) is a composite key made of two foreign keys, and it enforces a rule: one line per product in each order.
From ER model to CREATE TABLE
New requirement: “A customer can save products to a wishlist. A customer can save many products, and a product can be saved by many customers.” That is many-to-many, so we need a junction table. Here is the mapping we use:
| in the ER model | in the database |
|---|---|
| entity | table |
| attribute | column |
| identifier | PRIMARY KEY |
| one-to-many | FOREIGN KEY on the “many” side |
| one-to-one | FOREIGN KEY that is also PRIMARY KEY or UNIQUE |
| many-to-many | junction table with two foreign keys |
First, two real mistakes. A foreign key can only point to a table that already exists:
CREATE TABLE wishlist_items (
customer_id integer NOT NULL REFERENCES customers (id),
product_id integer NOT NULL REFERENCES wishlist_products (id),
added_on date NOT NULL,
PRIMARY KEY (customer_id, product_id)
);
ERROR: relation "wishlist_products" does not exist
Create parent tables first. Second, a foreign key must point to a primary key or a unique column, and product names have no UNIQUE rule:
CREATE TABLE wishlist_items (
customer_id integer NOT NULL REFERENCES customers (id),
product_name text NOT NULL REFERENCES products (name),
added_on date NOT NULL,
PRIMARY KEY (customer_id, product_name)
);
ERROR: there is no unique constraint matching given keys for referenced table "products"
If two products shared a name, PostgreSQL would not know which row you mean. Point to the surrogate key instead:
CREATE TABLE wishlist_items (
customer_id integer NOT NULL REFERENCES customers (id),
product_id integer NOT NULL REFERENCES products (id),
added_on date NOT NULL,
PRIMARY KEY (customer_id, product_id)
);
INSERT INTO wishlist_items (customer_id, product_id, added_on) VALUES
(10, 9, '2026-11-01'),
(10, 8, '2026-11-01'),
(2, 9, '2026-11-03');
SELECT c.name AS customer, p.name AS product, w.added_on
FROM wishlist_items w
JOIN customers c ON c.id = w.customer_id
JOIN products p ON p.id = w.product_id
ORDER BY c.name, p.name;
CREATE TABLE
INSERT 0 3
customer | product | added_on
--------------+-----------------------------+------------
Lucas Martin | Ergonomic Chair | 2026-11-03
Omar Haddad | Ergonomic Chair | 2026-11-01
Omar Haddad | Noise-Cancelling Headphones | 2026-11-01
(3 rows)
Omar saved two products and the chair was saved by two customers: many-to-many.
The foreign keys at work
Now the design protects the data. Try a product that does not exist, the same product twice, and deleting a saved product:
INSERT INTO wishlist_items (customer_id, product_id, added_on) VALUES (10, 99, '2026-11-04');
INSERT INTO wishlist_items (customer_id, product_id, added_on) VALUES (10, 9, '2026-11-04');
DELETE FROM products WHERE id = 9;
ERROR: insert or update on table "wishlist_items" violates foreign key constraint "wishlist_items_product_id_fkey"
DETAIL: Key (product_id)=(99) is not present in table "products".
ERROR: duplicate key value violates unique constraint "wishlist_items_pkey"
DETAIL: Key (customer_id, product_id)=(10, 9) already exists.
ERROR: update or delete on table "products" violates foreign key constraint "wishlist_items_product_id_fkey" on table "wishlist_items"
DETAIL: Key (id)=(9) is still referenced from table "wishlist_items".
Before the wishlist existed, deleting product 9 worked, because nobody had ordered it (we tested this in a transaction and rolled it back, as in Lesson 19). The default action is NO ACTION, which blocks the delete; ON DELETE CASCADE would delete the wishlist lines too (PostgreSQL docs: Constraints).
Try it yourself
Exercise 1: The keys of order_items
Use pg_constraint to list only the primary key and foreign keys of order_items. Which two tables does it join?
Exercise 2: A one-to-many shipments table
One order can be sent in several shipments. Create shipments (an identity id, order_id, shipped_on, carrier), add a shipment for order 19, then try one for order 99.
Exercise 3: Wishlist count per product
With the wishlist rows above, show how many customers saved each product, including products nobody saved. Show the top 4.
Solutions
Solution 1
SELECT conname, pg_get_constraintdef(oid) AS definition
FROM pg_constraint
WHERE conrelid = 'order_items'::regclass
AND contype IN ('p', 'f')
ORDER BY conname;
conname | definition
-----------------------------+--------------------------------------------------
order_items_order_id_fkey | FOREIGN KEY (order_id) REFERENCES orders(id)
order_items_pkey | PRIMARY KEY (order_id, product_id)
order_items_product_id_fkey | FOREIGN KEY (product_id) REFERENCES products(id)
(3 rows)
It joins orders and products, and its primary key is made of the two foreign keys.
Solution 2
CREATE TABLE shipments (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
order_id integer NOT NULL REFERENCES orders (id),
shipped_on date NOT NULL,
carrier text NOT NULL
);
INSERT INTO shipments (order_id, shipped_on, carrier) VALUES (19, '2026-10-15', 'TCS');
INSERT INTO shipments (order_id, shipped_on, carrier) VALUES (99, '2026-10-15', 'TCS');
CREATE TABLE
INSERT 0 1
ERROR: insert or update on table "shipments" violates foreign key constraint "shipments_order_id_fkey"
DETAIL: Key (order_id)=(99) is not present in table "orders".
order_id is not unique, so one order can have many shipments.
Solution 3
SELECT p.name, COUNT(w.customer_id) AS saved_by
FROM products p
LEFT JOIN wishlist_items w ON w.product_id = p.id
GROUP BY p.id, p.name
ORDER BY saved_by DESC, p.name
LIMIT 4;
name | saved_by
-----------------------------+----------
Ergonomic Chair | 2
Noise-Cancelling Headphones | 1
Desk Lamp | 0
Gel Pens 10-Pack | 0
(4 rows)
COUNT(w.customer_id) counts 0 for products with no match, as in Lesson 9.
When you finish, drop the practice tables (nothing points to them):
DROP TABLE shipments, wishlist_items, customer_profiles;
DROP TABLE
Common mistakes
- Putting the foreign key on the wrong side. It belongs on the “many” side:
orders.customer_id. - Referencing a column that is not unique.
there is no unique constraint matching given keys for referenced table "products". Reference the primary key. - Creating the child table first.
relation "wishlist_products" does not exist. Create parent tables first. - Forgetting the composite primary key on a junction table. Without
PRIMARY KEY (customer_id, product_id), the same pair can be saved twice. - Choosing a natural key that can be NULL or can change.
column "email" of relation "customers" contains null values. Use a surrogateidand keep the natural valueUNIQUE.
Frequently asked questions
What is the difference between an ER diagram and a database schema?
An ER diagram is a picture of the entities and relationships, often drawn before any table exists. The schema is the real set of tables, columns and constraints. Our pg_constraint query read the schema.
How do you show a many-to-many relationship in an ER diagram?
In an early sketch, draw one line with a crow’s foot on both ends. In the database, it becomes a junction table, like order_items, with two one-to-many lines going into it.
Should I use a natural key or a surrogate key?
A common choice is a surrogate key (an identity id) as the primary key, with natural values like email kept UNIQUE. A key built from existing columns is fine when it is short, never NULL and never changes, like the (order_id, product_id) pair in a junction table.
Summary
- Database design turns entities into tables, attributes into columns and relationships into foreign keys.
- Crow’s foot notation shows cardinality with a ring (zero), a dash (one) and a crow’s foot (many).
- One-to-many puts the foreign key on the “many” side; one-to-one makes that foreign key unique; many-to-many needs a junction table.
- A candidate key is a minimal set of columns that is unique and never NULL; the primary key is the one you pick, often a surrogate
id. - Foreign keys point to a primary key or unique column and block orphan rows and unsafe deletes.
Next lesson
Next: Lesson 29, Database Normalization: 1NF, 2NF, 3NF and BCNF With Examples.
Sources
- PostgreSQL documentation: Constraints (primary keys, foreign keys, many-to-many example, ON DELETE)
- PostgreSQL documentation: pg_constraint
- Peter Chen: The Entity-Relationship Model, Toward a Unified View of Data (ACM TODS, 1976)
- University of Regina: Crow’s Foot Notation
- Practical Databases (Runestone): ERD alternatives and variations





