Database Design & Normalization – SQL
Avoiding redundancy: 1NF, 2NF, 3NF, relationships, and when to denormalize deliberately.
Normalization splits tables so that each fact is stored exactly once. This avoids anomalies: changes in several places (update anomaly), missing master data without transaction data (insert anomaly), and accidental data loss (delete anomaly). The starting point is a typical "Excel table":
-- Bad: everything in one table
bestellung_id | kunde_name | kunde_stadt | produkte | preise
1 | Ada | Berlin | Laptop, Maus | 999, 25
5 | Ada | Berlin | Maus, Kaffee | 25, 8.5First normal form (1NF): each cell contains exactly one atomic value, no lists ("Laptop, Maus") and no repeating columns (produkt1, produkt2). Second normal form (2NF): additionally, every non-key attribute depends on the entire key (relevant for composite keys – e.g. preis belongs to the product, not to the combination of order and product). Third normal form (3NF): no transitive dependencies – an attribute depends only on the key, not on another non-key attribute (e.g. postal code → city).
-- Result: the familiar schema
-- kunden(id, name, stadt) -- customer data once
-- produkte(id, name, kategorie, preis) -- product data once
-- bestellungen(id, kunde_id, datum, status) -- 1:n to kunden
-- bestellpositionen(bestellung_id, produkt_id, menge) -- n:m between orders and products
-- n:m always needs a junction table with foreign keys to both sides:
CREATE TABLE produkt_tags (
produkt_id INTEGER NOT NULL REFERENCES produkte(id),
tag_id INTEGER NOT NULL REFERENCES tags(id),
PRIMARY KEY (produkt_id, tag_id)
);Relationships: 1:1 (rare, usually a split-out), 1:n (foreign key on the n side), and n:m (junction table). Choose primary keys that are stable and meaningless (surrogate keys such as id or UUID) – an email address as a key will change at some point.
produkte.preis changes later.