Database design: keys, relationships and normalization

Advanced  Nov 20, 2026

Design tables that avoid duplicated data: primary keys, foreign keys, one-to-many and many-to-many relationships.

Database design: keys, relationships and normalization

Good design is decided before you write code. A poor design causes duplicated data, mistakes and slow queries that are hard to fix later.

The steps of this tutorial at a glance.
The steps of this tutorial at a glance.

The goal of normalization

Store each fact once. If a customer’s phone number is stored in 50 order rows, changing it means 50 updates, and one will be missed.

The goal of normalization
The goal of normalization

A bad table

| order_id | customer_name | customer_phone | product | price |
|---|---|---|---|---|
| 1 | Ali | 0300… | Pen | 50 |
| 2 | Ali | 0300… | Book | 400 |

The customer details are repeated.

The fix: separate tables

CREATE TABLE customers (
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  phone VARCHAR(30) NOT NULL
) ENGINE=InnoDB;

CREATE TABLE orders (
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  customer_id INT UNSIGNED NOT NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (customer_id) REFERENCES customers(id)
) ENGINE=InnoDB;
The table described by the SQL above.
The table described by the SQL above.
How the code in this section fits into the page.
How the code in this section fits into the page.

Relationship types

  • One-to-many: one customer has many orders. Put the foreign key on the “many” side (orders.customer_id).
  • Many-to-many: an order has many products and a product is in many orders. Use a linking table:
CREATE TABLE order_items (
  order_id   INT UNSIGNED NOT NULL,
  product_id INT UNSIGNED NOT NULL,
  quantity   INT UNSIGNED NOT NULL DEFAULT 1,
  unit_price DECIMAL(10,2) NOT NULL,
  PRIMARY KEY (order_id, product_id),
  FOREIGN KEY (order_id)   REFERENCES orders(id)   ON DELETE CASCADE,
  FOREIGN KEY (product_id) REFERENCES products(id)
) ENGINE=InnoDB;

Note unit_price is copied at the time of sale on purpose: later price changes must not rewrite old orders. Deliberate copies like this are fine; accidental ones are not.

The table described by the SQL above.
The table described by the SQL above.

Practical rules

  • Every table has a primary key.
  • Use the smallest suitable type (INT, DATE, DECIMAL for money, never FLOAT).
  • Use NOT NULL where a value is required, and UNIQUE where duplicates must be impossible.
  • Use InnoDB for foreign keys and transactions, and utf8mb4 for text.
  • Index the columns you filter, join and sort by.
  • Draw the tables and relationships on paper before you create them.
The main points of this section.
The main points of this section.

When to denormalize

For reports and read-heavy pages, a copied or summary column can be faster. Do it deliberately, document it, and keep it updated, after you have measured a real problem.

More tutorials