ER diagrams: designing tables and relationships before you build them

An entity relationship diagram is the blueprint of a database. It shows what you store, which attributes each thing has and how everything connects. Once the diagram is right, the tables, keys and junction tables follow almost automatically.

In short: entities become tables, attributes become columns and relationships become keys. In a one-to-many relationship the foreign key goes on the "many" side (an order stores its customer). A many-to-many relationship needs a junction table with two foreign keys and the primary key PRIMARY KEY (product_id, supplier_id).

What you should know first: primary and foreign keys and normalization.

Try it now

The shop buys from several suppliers. Copy paper comes from two of them, and each supplier offers several products. That relationship doesn't fit into either table; it needs one of its own.

Task A product can come from several suppliers, and a supplier delivers several products: a many-to-many relationship. Create the junction table product_suppliers with product_id (whole number, required, foreign key to products), supplier_id (whole number, required, foreign key to suppliers) and unit_cost (decimal number). Each pair of product and supplier may appear only once. To check it, the exercise adds supplier offers (one pair twice and one with no product, both skipped with INSERT OR IGNORE) and shows in references_table which tables your foreign keys point to.

products 12 rows, 5 columns
product_idnamecategorypricestock
1Copy paper, 500 sheetsPaper4.99420
2Blue ballpoint pens, 10-packWriting3.49310
3Lever arch file, grayFiling2.79185
4Comfort office chairFurniture18912
5Standing deskFurniture4495
6Black ink cartridgePrinter supplies24.964
7Yellow sticky notes, 12 padsWriting6.990
8Mono laser printer L30Electronics2198
927-inch monitorElectronics27915
10Notebook A5, ruledPaper5.49140
11Black toner XLPrinter supplies89.922
12Cross-cut shredderElectronics1290
suppliers 5 rows, 4 columns
supplier_idnamecityphone
1Northfield Paper Co.Albany518-555-0120
2Lindon Stationery LtdSheffield0114 496 0350
3Crane Office FurnitureGrand Rapids616-555-0175
4Eastgate Tech SupplyRaleigh919-555-0148
5Summit Print SupplyDenver303-555-0166

The three building blocks

  • Entity: a thing you store data about, such as a customer, an order or a product. In the diagram it's a box, in the database a table.
  • Attribute: a property of the entity, such as name or price. It becomes a column. The attribute that makes each row unique becomes the primary key.
  • Relationship: how two entities are connected, such as "customer places order". It becomes a foreign key or a junction table.

The ER diagram of the practice database

Here is how the shop's five tables fit together, drawn in the widely used crow's foot notation:

ER diagram of the practice database: one customer has many orders, one order has many order items, one product appears in many order items, one employee handles many orders and manages many employees. customers PK customer_id name city country customer_since segment phone orders PK order_id FK customer_id order_date status FK employee_id order_items PK FK order_id PK FK product_id quantity unit_price employees PK employee_id first_name last_name department salary hire_date FK manager_id products PK product_id name category price stock exactly one many PK primary key FK foreign key
A bar at the end of a line means "exactly one", the crow's foot means "many". Simplified: this diagram doesn't show whether a side is required or optional.

Read every line in both directions. A customer places many orders, and an order belongs to exactly one customer. An employee handles many orders. The line on the left of employees loops back to the same table: one employee manages many employees, and manager_id points to another row in employees.

Cardinality: one-to-one, one-to-many, many-to-many

Cardinality tells you how many rows on each side belong together, and it decides where the foreign key goes:

RelationshipExampleHow it becomes tables
One-to-many (1:n)customer and ordersforeign key customer_id in orders, on the "many" side
Many-to-many (n:m)orders and productsjunction table order_items with order_id and product_id
One-to-one (1:1)employee and company carforeign key with UNIQUE in one of the two tables

Why does the foreign key always sit on the "many" side? An order has exactly one customer, so one column is enough. A customer has many orders, so customers would need an open-ended number of columns, which first normal form already rules out.

Many-to-many becomes a junction table

An order contains many products, and a product appears in many orders. That's why the diagram has no direct line between orders and products. order_items sits in between: each row links one order to one product, so one many-to-many relationship turns into two one-to-many relationships. The primary key on both columns makes sure each pair appears only once. Quantity and unit price live there as well, because they belong to the pair, not to the order or the product alone.

To query across it, you join through the junction table:

SELECT o.order_id, c.name AS customer, pr.name AS product, i.quantity
FROM orders o
JOIN customers c    ON c.customer_id = o.customer_id
JOIN order_items i  ON i.order_id = o.order_id
JOIN products pr    ON pr.product_id = i.product_id
WHERE o.order_id = 1007;
order_idcustomerproductquantity
1007Northline Printing CoCopy paper, 500 sheets20
1007Northline Printing CoMono laser printer L302
1007Northline Printing CoBlack toner XL4

More practice

The junction table between products and suppliers now exists and has data in it. Query it the same way as order_items: the path from products to suppliers runs through product_suppliers.

Task Purchasing is comparing offers for paper. For every product in the category Paper, show the product name, the supplier name and the unit cost. Products and suppliers are linked through the junction table product_suppliers.

products 12 rows, 5 columns
product_idnamecategorypricestock
1Copy paper, 500 sheetsPaper4.99420
2Blue ballpoint pens, 10-packWriting3.49310
3Lever arch file, grayFiling2.79185
4Comfort office chairFurniture18912
5Standing deskFurniture4495
6Black ink cartridgePrinter supplies24.964
7Yellow sticky notes, 12 padsWriting6.990
8Mono laser printer L30Electronics2198
927-inch monitorElectronics27915
10Notebook A5, ruledPaper5.49140
11Black toner XLPrinter supplies89.922
12Cross-cut shredderElectronics1290
product_suppliers 14 rows, 3 columns
product_idsupplier_idunit_cost
113.1
153.25
1012.95
1053.05
221.8
321.45
723.6
43112
53298
6413.5
84142
94189
11452
6514.2
suppliers 5 rows, 4 columns
supplier_idnamecityphone
1Northfield Paper Co.Albany518-555-0120
2Lindon Stationery LtdSheffield0114 496 0350
3Crane Office FurnitureGrand Rapids616-555-0175
4Eastgate Tech SupplyRaleigh919-555-0148
5Summit Print SupplyDenver303-555-0166

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

Required or optional

Cardinality also covers whether a side may be missing. Every order has a customer, so customer_id is NOT NULL. Open orders don't have an employee yet, so employee_id may be empty. And a product can have zero suppliers. In a query, "optional" nearly always means LEFT JOIN, otherwise exactly those rows disappear.

Task A product with only one source is a risk, and one with no supplier at all is worse. List every product with its name and the number of suppliers in product_suppliers, including products with no supplier, which should show 0.

products 12 rows, 5 columns
product_idnamecategorypricestock
1Copy paper, 500 sheetsPaper4.99420
2Blue ballpoint pens, 10-packWriting3.49310
3Lever arch file, grayFiling2.79185
4Comfort office chairFurniture18912
5Standing deskFurniture4495
6Black ink cartridgePrinter supplies24.964
7Yellow sticky notes, 12 padsWriting6.990
8Mono laser printer L30Electronics2198
927-inch monitorElectronics27915
10Notebook A5, ruledPaper5.49140
11Black toner XLPrinter supplies89.922
12Cross-cut shredderElectronics1290
product_suppliers 14 rows, 3 columns
product_idsupplier_idunit_cost
113.1
153.25
1012.95
1053.05
221.8
321.45
723.6
43112
53298
6413.5
84142
94189
11452
6514.2

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

Common mistakes

Foreign key on the wrong side

Put order_id into customers instead of customer_id into orders, and each customer has room for just one order. When you design, check that the table on the "many" side gets the foreign key.

Many-to-many without a junction table

A column suppliers in products holding "Northfield Paper, Summit Print" breaks first normal form. Columns supplier1 and supplier2 don't solve it either, because the third supplier has nowhere to go.

Junction table without a composite key

Without PRIMARY KEY (product_id, supplier_id) the same pair can be stored twice. The exercise then says: "After your changes: The check shows 13 rows, expected: 12 rows." Write PRIMARY KEY after both columns and you get "table "product_suppliers" has more than one primary key".

COUNT(*) with optional relationships

After a LEFT JOIN, COUNT(*) counts the empty row too, so a product without a supplier gets 1 instead of 0. The exercise reports that the column and row count match but the values don't. Count a column from the right-hand table instead. Use JOIN instead of LEFT JOIN and it tells you the query returns only 11 rows when 12 are wanted.

Auto-numbered keys in MySQL, PostgreSQL, SQL Server and SQLite

Every entity needs a primary key, usually a number the database assigns itself. The syntax differs:

DatabaseAutomatic numberNote
MySQLid INT NOT NULL AUTO_INCREMENT with PRIMARY KEY (id)leave the value out of the INSERT and MySQL assigns the next number
PostgreSQLid bigint GENERATED ALWAYS AS IDENTITYwith BY DEFAULT instead of ALWAYS you may insert your own values
SQL Serverid INT IDENTITY(1, 1)IDENTITY alone doesn't guarantee uniqueness; that takes PRIMARY KEY or UNIQUE
SQLite (these exercises)id INTEGER PRIMARY KEYgets a number automatically when you don't supply one; AUTOINCREMENT is usually not needed

Sources: MySQL Reference Manual (Using AUTO_INCREMENT), PostgreSQL documentation (Identity Columns), Microsoft Learn (IDENTITY Property), sqlite.org (SQLite Autoincrement).

FAQ

What does ER stand for?

Entity relationship. The model describes your data independently of the database product it will end up in.

Crow's foot or Chen notation?

Chen notation draws relationships as diamonds and writes 1, n and m on the lines. Crow's foot notation shows tables with their columns, which makes it a natural fit when you design in SQL. Both describe the same thing.

Does a junction table need its own ID?

Not necessarily. The composite key made of both foreign keys is enough and blocks duplicate pairs. If you do give it its own ID, add UNIQUE (product_id, supplier_id) so the pairs stay unique.

When is one-to-one worth it?

Rarely. A typical case is data that only applies to a few rows or needs extra protection, such as salary details kept apart from an employee's basic record.

Up next: indexes

Your data model is in place. Indexes keep lookups on keys and joins fast even when tables grow large.

Learn about indexes

Write to us

Choose language

Select your preferred language