MyMisPal
← SQL lessons
Lesson 12 of 12

Relationships and normalisation

Database design starts with one question: how are things related? That is exactly what an ERD captures.

employees badges 1 : 1

One-to-one: each employee has one access badge, and each badge belongs to one employee.

departments employees 1 : N

One-to-many: a department has many employees; an employee belongs to one department. The foreign key always sits on the “many” side: employees.dept_id.

orders products M : N

Many-to-many: an order holds many products, and a product appears in many orders.

A many-to-many relationship cannot be stored directly. We resolve it with a bridge table: one order has many products and one product appears in many orders, so order_items links them with two foreign keys.

Normalisation means splitting data into tables so each fact is stored once. Look at this bad table:

order_idcustomercityproducts
1Al Noor TradingRiyadhLaptop Pro 14, 27-inch Monitor
4Al Noor TradingRiyadhWireless Router, Network Switch 24-port
13Al Noor TradingRiyadhLaptop Pro 14, Ergonomic Chair

The problem: the customer's name and city repeat on every order, and products are crammed into one cell. If the customer moves, you must edit every row, and missing one leaves contradictory data.

1NFOne value per cell, no repeating groups.
2NF1NF + every column depends on the whole key, not part of it.
3NF2NF + no column depends on another non-key column (city depends on the customer, not the order).

The database we have used is in 3NF, which is what made the joins possible. In the next phase we build the ERD Studio, where you draw these relationships and get SQL generated automatically.

Exercises

Exercise 1

Use the bridge table: show product name and quantity for every product in order 2.

Spotted a mistake on this page, or have an idea to improve the site?