← 講座に戻る: SQL and databases from scratch

Normalization and week 7 review

動画は近日公開

We have talked about how to query and how to do it fast. The underlying question is missing: how do you decide which tables to create and which columns go in each? Normalization is the set of rules to split data into tables so that each fact is stored only once. The goal is not elegance, but avoiding anomalies: errors that appear when the same data is repeated in many places and someone updates it only in some.

A problematic design

Look at a single table that mixes everything, like one made by someone coming from a spreadsheet. Each row repeats the customer's name and city and the product data. It has three classic problems. Update anomaly: if Ana changes city, it must be fixed in every row; if you forget one, the database is contradictory. Insert anomaly: you cannot register a new customer until they place an order. Delete anomaly: if you delete a customer's only order, you also lose their personal data.

sql
-- BAD design: everything in one table (do not copy this)
CREATE TABLE orders_flat (
  order_id       INTEGER,
  order_date     DATE,
  customer_name  TEXT,
  customer_city  TEXT,
  product_name   TEXT,
  product_price  NUMERIC(10,2),
  quantity       INTEGER
);

-- Ana appears in every one of her orders; a typo like 'Madird' in one row
-- creates a second, inconsistent version of the same customer.

The normal forms

  • First normal form (1NF): each cell stores a single value (no lists like 'red, blue' in a column) and there are no repeated column groups (phone1, phone2, phone3). Each row is identifiable by a key.
  • Second normal form (2NF): meets 1NF and every column depends on the whole key, not just part of it. It affects composite keys: in an order line with key (order, product), the product name depends only on the product, so it goes in its own table.
  • Third normal form (3NF): meets 2NF and no column depends on another column that is not the key. If you store city and country in the customers table, the country depends on the city, not on the customer: it goes apart.

A phrase to remember 3NF: every column depends on the key, the whole key and nothing but the key. Our shop already follows that design: customer data is in customers, product data in products, order data in orders and the relationship between orders and products in order_items. Only one point is debatable: products.category repeats the category text in each product. It could be moved to its own table, which allows renaming a category in a single place and avoids typing errors.

sql
-- Normalizing the category into its own table (in a COPY, to keep our shop intact)
CREATE TABLE categories (
  category_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  name        TEXT NOT NULL UNIQUE
);

INSERT INTO categories (name) SELECT DISTINCT category FROM products;

CREATE TABLE products_v2 AS
SELECT p.product_id, p.name, c.category_id, p.price, p.stock
FROM products p
JOIN categories c ON c.name = p.category;

-- Same report as before, now with one extra JOIN
SELECT c.name AS category, COUNT(*) AS products
FROM products_v2 v
JOIN categories c ON c.category_id = v.category_id
GROUP BY c.name
ORDER BY c.name;

Denormalizing: when and why

Normalizing has a price: more tables and more JOINs. Sometimes the rule is broken on purpose, and this is called denormalizing. An example already in the shop: order_items.unit_price repeats the product price, but it is correct because it represents the historical price charged, which must not change if the catalog goes up. Other legitimate cases are report tables that store precomputed totals for fast queries. The practical rule: start normalized and denormalize only with a measured reason, knowing that you take on the responsibility of keeping the data consistent.

理解度チェック

問題 1 / 6

What does a B-tree index do?

✎ マイノート

このブラウザにのみ保存されます。ログインするとアカウントに保存できます。0/5000 文字

← 前へ次へ →