Database Design: Entities, Relationships and ER Diagrams
How to design a relational database: finding entities and attributes in requirements, choosing primary keys, one-to-many, one-to-one and many-to-many relationships, junction tables, optional and mandatory participation, recursive relationships, and reading ER diagrams in crow's foot notation.
kvi5hnuCode Sprout team member12 min readOn this page
Every query in this course has run against tables someone designed: customers, orders, order_items, products. Good design is why those queries are simple. Each fact is stored once, every relationship is a join on a key, and the database itself rejects nonsense such as an order line for an order that doesn't exist. Poor design shows up later as duplicated data, contradictory values, and queries full of workarounds.
This article covers the first step of design: turning requirements into entities, attributes and relationships, and drawing them as an entity-relationship (ER) diagram. Article 51 covers normalisation, the rules for checking a design, and Part 11 covers the SQL that creates the tables.
From requirements to entities and attributes
Design starts with a description of what the system must record. Take this one for the shop:
Customers place orders. Each order has one or more lines, each for a quantity of one product at the price charged. Guests can order without an account. Products come from suppliers; a product may be available from several suppliers, each with its own cost and delivery time. Staff members report to a manager.
The nouns suggest entities, the things the system stores facts about: customer, order, order line, product, supplier, staff member. An entity becomes a table, and each instance (one particular customer) becomes a row.
The facts about each entity are its attributes, which become columns: a customer's name and city, an order's date and status, a product's name and price. For each attribute, decide:
- Is it atomic? Store first and last names, or a street and a postcode, separately if anything will search, sort or validate them separately. A single
addresstext is fine only if it's just printed. - Is it a fact about this entity? A product's price belongs to the product. The price charged on an order belongs to the order line, because it can differ from today's price.
- Is it derived? An order's total can be computed from its lines, so it usually isn't stored (article 51 discusses when to store it anyway).
- Can it be missing? A customer's city might be unknown, but an order always has a date. That becomes
NULLversusNOT NULL.
The verbs suggest relationships: customers place orders, orders have lines, suppliers supply products, staff report to managers.
Keys
Every entity needs a primary key: a column, or set of columns, whose value identifies exactly one row and never changes.
- A natural key is a real-world identifier that's already unique: an ISBN, a country code, a product's SKU. It's meaningful, but real-world identifiers change more often than expected (people change email addresses, companies renumber products), and some aren't as unique as they seem.
- A surrogate key is a meaningless number or UUID generated by the database, like
customer_id. It never needs to change, it's compact, and joins on it are fast. Article 54 covers how to generate them.
The common practice is a surrogate primary key, plus a UNIQUE constraint on any natural key, so that both "one row per customer ID" and "one customer per email address" are enforced. A table whose rows are identified by a combination of columns, such as order_items by (order_id, product_id), has a composite key.
Relationships
A relationship has a cardinality, the maximum number of rows on each side, and a participation, whether a row must take part at all.
One-to-many
One customer places many orders; each order belongs to one customer. This is the most common relationship, and it's implemented with a foreign key on the "many" side: orders.customer_id refers to customers.customer_id. The "one" side needs nothing extra.
A foreign key column can't hold a list, so the foreign key always goes on the many side: one order can have only one customer_id, but many orders can have the same one.
Optional and mandatory participation
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
\pset null '(null)'
-- Optional and mandatory participation
-- orders.customer_id allows NULL: an order may exist without a customer (guest checkout)
SELECT order_id, customer_id FROM orders WHERE customer_id IS NULL;
-- order_items.order_id is NOT NULL (part of the key) and must match an order: no line without an order
INSERT INTO order_items VALUES (999, 1, 1, 249.99);
order_id | customer_id
----------+-------------
106 | (null)
(1 row)
psql:/workspace/solution.sql:69: ERROR: insert or update on table "order_items" violates foreign key constraint "order_items_order_id_fkey"
DETAIL: Key (order_id)=(999) is not present in table "orders".
Participation is enforced with NULL and NOT NULL:
- Optional:
orders.customer_idallows NULL, because guests can order without an account. Order 106 has no customer. - Mandatory:
order_items.order_idisNOT NULL(it's part of the primary key), so every line must belong to an order, and the foreign key makes sure that order exists. The insert for order 999 fails.
"A customer has at least one order" can't be declared this way: the foreign key is on the order side. Rules like that are checked by application logic, triggers (article 65) or deferred constraints, and they're often relaxed in practice: a customer can register before ordering.
One-to-one
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
\pset null '(null)'
-- A one-to-one relationship: the primary key is also the foreign key
CREATE TABLE product_dimensions (
product_id INTEGER PRIMARY KEY REFERENCES products (product_id),
length_cm INTEGER NOT NULL,
width_cm INTEGER NOT NULL,
height_cm INTEGER NOT NULL
);
INSERT INTO product_dimensions VALUES (1, 45, 15, 15), (5, 60, 30, 20);
SELECT p.name, d.length_cm, d.width_cm, d.height_cm
FROM products p
LEFT JOIN product_dimensions d ON d.product_id = p.product_id
WHERE p.category IN ('tents', 'packs')
ORDER BY p.product_id;
-- A second row for the same product is rejected: at most one per product
INSERT INTO product_dimensions VALUES (1, 50, 16, 16);
name | length_cm | width_cm | height_cm
-------------------+-----------+----------+-----------
Ridge 2 tent | 45 | 15 | 15
Summit 4 tent | (null) | (null) | (null)
Trail 30 backpack | 60 | 30 | 20
Day 18 backpack | (null) | (null) | (null)
(4 rows)
psql:/workspace/solution.sql:80: ERROR: duplicate key value violates unique constraint "product_dimensions_pkey"
DETAIL: Key (product_id)=(1) already exists.
Each product has at most one set of packed dimensions. Making product_id both the primary key and a foreign key of product_dimensions enforces both rules: the dimensions must belong to an existing product, and a product can't have two sets. A UNIQUE foreign key column does the same job when the table has its own primary key.
Why not put the dimensions in products? Usually you should. Separate one-to-one tables are useful when the extra columns apply only to some rows (only packs and tents have dimensions here), when they're large or rarely read, or when they have different access rules, such as salary details kept apart from employee records.
Many-to-many and junction tables
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- A many-to-many relationship: suppliers supply many products, products have many suppliers
CREATE TABLE suppliers (
supplier_id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
country TEXT NOT NULL
);
INSERT INTO suppliers VALUES
(1, 'Northface Textiles', 'UK'),
(2, 'Pune Outdoor Works', 'India'),
(3, 'Kestrel Packs Ltd', 'UK');
-- The junction table: one row per (supplier, product) pair, with facts about the pair
CREATE TABLE supplier_products (
supplier_id INTEGER REFERENCES suppliers (supplier_id),
product_id INTEGER REFERENCES products (product_id),
unit_cost DECIMAL(8, 2) NOT NULL,
lead_days INTEGER NOT NULL,
PRIMARY KEY (supplier_id, product_id)
);
INSERT INTO supplier_products VALUES
(1, 7, 6.50, 10),
(2, 1, 150.00, 30), (2, 2, 310.00, 30), (2, 7, 5.80, 21),
(3, 5, 48.00, 14), (3, 6, 29.00, 14);
-- Products with more than one supplier, and the cheapest source
SELECT p.name,
COUNT(*) AS suppliers,
MIN(sp.unit_cost) AS best_cost,
(array_agg(s.name ORDER BY sp.unit_cost))[1] AS cheapest_supplier
FROM products p
JOIN supplier_products sp ON sp.product_id = p.product_id
JOIN suppliers s ON s.supplier_id = sp.supplier_id
GROUP BY p.product_id, p.name
ORDER BY suppliers DESC, p.name;
-- The same pair can't be recorded twice
INSERT INTO supplier_products VALUES (3, 5, 47.00, 14);
name | suppliers | best_cost | cheapest_supplier
-------------------+-----------+-----------+--------------------
Merino socks | 2 | 5.80 | Pune Outdoor Works
Day 18 backpack | 1 | 29.00 | Kestrel Packs Ltd
Ridge 2 tent | 1 | 150.00 | Pune Outdoor Works
Summit 4 tent | 1 | 310.00 | Pune Outdoor Works
Trail 30 backpack | 1 | 48.00 | Kestrel Packs Ltd
(5 rows)
psql:/workspace/solution.sql:98: ERROR: duplicate key value violates unique constraint "supplier_products_pkey"
DETAIL: Key (supplier_id, product_id)=(3, 5) already exists.
A supplier supplies many products, and a product can come from many suppliers. A relational table can't store this directly: neither table can hold a list of the other's keys. The solution is a junction table (also called a link, bridge or associative table), supplier_products, with:
- a foreign key to each side
- a composite primary key of both foreign keys, so the same pair can't be recorded twice, as the last insert shows
- the attributes of the relationship itself: a supplier's cost and lead time for a product are facts about the pair, not about the supplier or the product alone
A many-to-many relationship is really two one-to-many relationships meeting at the junction table. order_items is one too: it links orders and products, and carries the quantity and price charged. Queries go through it with two joins, and here they find that the socks have two suppliers, the cheapest in Pune.
The most common mistake is storing a list in a column instead, such as products.supplier_ids = '1,2'. It can't be joined, indexed, validated against suppliers or updated safely, and it has nowhere to put the cost (article 51 calls this a violation of first normal form).
Attributes of relationships
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- An attribute that belongs to a relationship, not to either entity:
-- the price charged is a fact about (order, product), so it lives on order_items
SELECT oi.order_id, p.name, p.price AS current_price, oi.unit_price AS price_charged
FROM order_items oi
JOIN products p ON p.product_id = oi.product_id
WHERE oi.unit_price <> p.price;
order_id | name | current_price | price_charged
----------+--------------+---------------+---------------
103 | Merino socks | 16.00 | 15.00
(1 row)
Attributes go wherever they're facts about. The price charged depends on the order and the product together, so it lives on order_items, and it records history correctly: the socks were sold at 15.00 in order 103 although they cost 16.00 today. If the order only referred to the current product price, every change of price would rewrite the past.
Recursive relationships
\pset null '(null)'
-- A recursive (self-referencing) relationship: each staff member may have a manager
CREATE TABLE staff (
staff_id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
role TEXT NOT NULL,
manager_id INTEGER REFERENCES staff (staff_id)
);
INSERT INTO staff VALUES
(1, 'Ines Moreau', 'store manager', NULL),
(2, 'Kofi Mensah', 'warehouse lead', 1),
(3, 'Lena Fischer', 'buyer', 1),
(4, 'Omar Siddiq', 'picker', 2),
(5, 'Ravi Iyer', 'picker', 2);
SELECT s.name, s.role, m.name AS manager
FROM staff s
LEFT JOIN staff m ON m.staff_id = s.manager_id
ORDER BY s.staff_id;
name | role | manager
--------------+----------------+-------------
Ines Moreau | store manager | (null)
Kofi Mensah | warehouse lead | Ines Moreau
Lena Fischer | buyer | Ines Moreau
Omar Siddiq | picker | Kofi Mensah
Ravi Iyer | picker | Kofi Mensah
(5 rows)
An entity can be related to itself: a staff member reports to another staff member. The foreign key manager_id points to the same table, and it's optional, because the top of the hierarchy has no manager. Querying it uses a self-join (article 14), or a recursive CTE for whole chains (articles 25 and 48). Customer referrals (referred_by) and category trees are the same pattern.
ER diagrams
An ER diagram draws the entities as boxes, listing their attributes and keys, and the relationships as lines between them. The most widely used style, crow's foot notation, marks each end of a line with its cardinality and participation:

Each end of a line has two symbols. The one nearer the box gives the maximum (a bar for one, a crow's foot for many), and the outer one gives the minimum (a circle for zero, a bar for one). Read a relationship from one entity, across the line, to the symbol at the other end:
- customers → orders: a customer places zero or more orders (circle and crow's foot at the orders end).
- orders → customers: an order belongs to zero or one customer (circle and bar at the customers end), because guests exist.
- orders → order_items: an order has one or more lines (bar and crow's foot). An empty order isn't allowed by the business rules, although, as noted above, the database can't enforce this minimum with a foreign key alone.
- products ↔ suppliers: many-to-many, drawn through the junction table
supplier_products.
Other notations exist: Chen notation, with diamonds for relationships, appears in textbooks, and UML class diagrams use 0..1 and 1..*. They express the same ideas. Tools such as dbdiagram.io, DBeaver, pgModeler and MySQL Workbench can draw diagrams from a schema, which is also a quick way to understand an unfamiliar database.
A design process
- Collect the requirements in plain sentences, including the awkward cases: guests, cancelled orders, products with no supplier, history that must be kept.
- List entities and attributes from the nouns, and decide each attribute's type and whether it can be missing.
- Choose keys: a surrogate primary key, plus
UNIQUEconstraints on natural keys. - Find relationships from the verbs, with their cardinality and participation. Resolve every many-to-many with a junction table.
- Draw the diagram and read every relationship out loud in both directions. Mistakes are easier to hear than to see.
- Normalise (article 51), then write the tables with constraints (article 52).
- Test with queries: write the questions the system must answer. If one needs string parsing or a dozen workarounds, the design is wrong.
What's current
- ER modelling hasn't changed in decades, but tools have: schema-as-code formats (DBML, Prisma schemas, migration files) generate diagrams and keep them in version control, so the diagram matches the real schema.
- PostgreSQL 18 added temporal constraints (with the
btree_gistextension for scalar key columns),PRIMARY KEYandUNIQUEwithWITHOUT OVERLAPSand foreign keys withPERIOD, so relationships that hold only during a time range can now be declared rather than coded by hand.
Common questions
Which side of a one-to-many relationship gets the foreign key? The many side. Each order stores its one customer's ID.
How do I store a many-to-many relationship? With a junction table holding a foreign key to each side, a composite primary key of the two, and any attributes of the relationship.
Natural or surrogate keys?
Usually a surrogate primary key, with UNIQUE constraints on natural identifiers.
When should I split one-to-one data into a separate table? When the columns apply to only some rows, are large or rarely used, or need different access rules. Otherwise, keep them in one table.
What does a circle mean in crow's foot notation? Zero: the relationship is optional on that side. A bar means one, and a crow's foot means many.
Summary
- Entities become tables, attributes become columns, and relationships become foreign keys.
- Choose a stable primary key for every table, usually a surrogate, and enforce natural keys with
UNIQUE. - One-to-many: a foreign key on the many side. Optional participation allows NULL, and mandatory uses
NOT NULL. - One-to-one: a foreign key that's also the primary key or unique.
- Many-to-many: a junction table with two foreign keys, a composite key and the relationship's own attributes.
- Put each attribute where it's a fact about, such as the price charged on the order line.
- Recursive relationships are foreign keys to the same table.
- ER diagrams in crow's foot notation show cardinality and participation at each end of every relationship.
Practice questions
A course has many students, and a student takes many courses. Each enrolment has a grade. Design the tables.
Answer
Three tables: students(student_id PK, ...), courses(course_id PK, ...) and a junction table enrolments(student_id FK, course_id FK, grade, PRIMARY KEY (student_id, course_id)). The grade is a fact about the pair, so it goes in the junction table.
Each employee has exactly one company car, and each car is assigned to at most one employee. Where does the foreign key go, and what constraint makes the relationship one-to-one?
Answer
Put car_id in the employees table as a NOT NULL UNIQUE foreign key. NOT NULL makes every employee have a car, the foreign key makes it a real car, and UNIQUE stops two employees sharing one car, which is what makes the relationship one-to-one rather than one-to-many. Cars without an employee simply don't appear in the column.
A design stores orders.product_ids as text such as '1,7'. Give three problems with it.
Answer
It can't have a foreign key, so invalid IDs are accepted. Finding orders for a product needs string matching, which can't use an index and matches '17' for '1' if done carelessly. And there's nowhere to store the quantity or price for each product. Use a junction table, order_items.
Why is the price charged stored on order_items, when products already has a price?
Answer
The price charged is a fact about a particular order line, and it must stay as it was when the order was placed. products.price is today's price and changes over time. Reading it for old orders would rewrite history.
Previous: Tricky SQL Problems and How to Solve Them
Next: Normalization: 1NF, 2NF, 3NF, BCNF and When to Denormalize

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.