Find a course

Module 4: Joining TablesLesson 7 of 1112 min

Keys, Relationships and Why Data Is Split Into Tables

Learn one-to-many and many-to-many relationships, how primary and foreign keys connect tables, and why normalization prevents duplicated data.

Step 1 of 13Learn

Why not one giant table?

Maya's original spreadsheet put everything about an order in one row: customer name, email and city, plus book title, author and price. Database designers call the problems this causes anomalies:

  • Update anomaly: Priya changes her email. It appears on 3 order rows. Update two and miss one, and the data now contradicts itself.
  • Insert anomaly: a new customer signs up but hasn't ordered yet. In an orders-only table there's nowhere to record them without inventing a fake order.
  • Delete anomaly: delete Ava's only order to correct a mistake, and you lose the only record that she exists.

The solution is normalization: organizing data so each fact is stored in exactly one place. In practice, that means splitting data into tables by the things it describes, here customers, orders and books, and linking them with keys.

Here are the customers and orders tables you'll join in the next lesson:

customers

customer_idnamecityemail
1Priya ShahAustinpriya@example.com
2Tom BeckerDenverNULL
3Lena OrtizAustinlena@example.com
4Marcus LeeBostonmarcus@example.com
5Ava NovakDenverava@example.com

orders

order_idcustomer_idorder_datetotal
10112026-01-0536.00
10232026-01-0942.00
10312026-02-1412.99
10442026-02-2059.50
10522026-03-0224.00
10612026-03-1521.00

Each customer's details are stored once. Orders refer to customers by customer_id. Notice two details you'll use later: customer 1 (Priya) has three orders, and customer 5 (Ava) has none.

Normalization has formal levels called normal forms, but the everyday rule of thumb is simple: if you find yourself typing the same information in many rows, it probably belongs in its own table. The trade-off is that answering questions now requires combining tables, which is exactly what joins do.

Step 2 of 13Practice · Sort into groups

Classify each problem with the one-big-table design.

Tap an item, then tap its group (or drag it there).

Step 3 of 13Practice · Diagram

One customer, many orders

One-to-many in the sample data: each order points to exactly one customer, but a customer can have any number of orders, including none.

Which customer is on the "one" side of the most orders?

Tap the shape that answers the question, then press Check.

One customer, many ordersHierarchy diagram: customers, Priya Shah (1), Tom Becker (2), Lena Ortiz (3), Marcus Lee (4), Ava Novak (5), Order 101, Order 103, Order 106, Order 105, Order 102, Order 104.customersPriya Shah (1)Order 101Order 103Order 106Tom Becker (2)Order 105Lena Ortiz (3)Order 102Marcus Lee (4)Order 104Ava Novak (5)
customers
Priya Shah (1)
Tom Becker (2)
Lena Ortiz (3)
Marcus Lee (4)
Ava Novak (5)

No orders yet. One-to-many allows zero.

Order 101
Order 103
Order 106
Order 105
Order 102
Order 104

Step 4 of 13Learn

Types of relationships

Tables relate to each other in three basic patterns.

One-to-many is by far the most common. One customer can place many orders, but each order belongs to exactly one customer. You implement it by putting a foreign key on the "many" side: orders.customer_id points to customers.customer_id. Other examples: one author has many books; one department has many employees.

One-to-one: each row in one table matches at most one row in another. For example, a users table and a user_settings table. It's often used to separate rarely used or sensitive columns. The foreign key also has a UNIQUE constraint.

Many-to-many: one order can contain many books, and one book can appear in many orders. You can't capture this with a single foreign key column. Instead, you add a junction table (also called a bridge or linking table):

order_items(order_id, book_id, quantity)

Each row says "this order included this book, this many times." The table has two foreign keys, and together (order_id, book_id) form its primary key, a composite key. Students and courses, actors and movies, and tags and blog posts all use the same pattern.

Foreign keys bring referential integrity: the database refuses an order whose customer_id doesn't exist in customers, and it can be told what to do when a customer is deleted: block the deletion, delete their orders too (ON DELETE CASCADE), or set the foreign key to NULL.

Drawing tables as boxes with lines between their keys, an entity-relationship diagram, is the usual first step in designing a database.

Step 5 of 13Compare

The three relationship types

AspectOne-to-oneOne-to-manyMany-to-many
ExampleEmployee and their badgeCustomer and ordersOrders and books
How oftenRareMost commonCommon
How it's builtForeign key with UNIQUEForeign key on the "many" sideA junction table with two foreign keys
Example tablebadges(employee_id UNIQUE)orders(customer_id)order_items(order_id, book_id)

Step 6 of 13Practice · Match the pairs

Match each pair of things to the relationship type it usually has.

Tap an answer, then tap the place where it belongs (or drag it there).

  1. Customers and orders
  2. Students and courses they enroll in
  3. Users and their single settings record
  4. enrollments(student_id, course_id)

Step 7 of 13Practice · Work it out

Using the orders table above, how many distinct customers have placed at least one order?

Step 8 of 13Note

Step 9 of 13Learn

Keys in practice

A few practical points about keys come up constantly.

Surrogate vs. natural keys. A natural key is a real-world identifier, like an ISBN for books or an email address for users. A surrogate key is an artificial number assigned by the database, like book_id. Natural keys seem convenient, but real-world identifiers change (people change email addresses), get reused, have formatting variations, or turn out not to be unique after all. Most designs use surrogate primary keys and enforce uniqueness of natural identifiers separately with a UNIQUE constraint.

Auto-generated IDs. Databases can generate surrogate keys automatically, with syntax that varies: SERIAL or GENERATED ALWAYS AS IDENTITY in PostgreSQL, AUTO_INCREMENT in MySQL, INTEGER PRIMARY KEY in SQLite, IDENTITY in SQL Server. You insert a row without the ID, and the database fills it in.

Indexes. The database automatically indexes primary keys so it can find a row by ID instantly instead of scanning the whole table. Foreign key columns are frequently joined and filtered on, so adding an index to them is a common performance step, although not every database adds one automatically.

Keys carry no meaning. Don't encode information into IDs, like making customer IDs start with a region code. When the customer moves, the ID would become wrong, and changing a primary key ripples through every table that references it.

Understanding keys is what makes joins click: a join is simply matching foreign key values to primary key values.

Step 10 of 13Compare

Natural key vs. surrogate key

AspectNatural keySurrogate key
ExampleEmail, ISBNcustomer_id 1, 2, 3
Meaning outside the databaseYesNone
Can changeOften (people change emails)Never needs to
Size and speedCan be long textSmall integer, fast to join
Keep uniqueness?Yes, add a UNIQUE constraintIt is the primary key

Step 11 of 13Note

Step 12 of 13Practice · True or false

To record which books appear in which orders, when an order can contain many books and a book can appear in many orders, you can simply add a book_id column to the orders table.

Step 13 of 13Practice · Choose one

Why do most database designs use a surrogate key such as customer_id rather than the customer's email address as the primary key?