SQL · Module 10 · Lesson 41 min read

Denormalization & Common Design Patterns

Denormalization – deliberate duplication

Breaking normalization on purpose for a good reason:

  • Performance: store expense_count on users instead of counting millions of rows on every page load
  • History / snapshots: an invoice must keep the price at the time of sale, even if the product price changes later → copy it into order_items.unit_price ✅ (this is actually correct modelling, not a hack)
  • Reporting: pre-aggregated summary tables or materialized views (Unit 13)

The cost

You must keep copies in sync — with triggers, application code or scheduled refreshes. Denormalize only when you've measured a need.

Pattern 1: Timestamps on every table

created_at TIMESTAMPTZ NOT NULL DEFAULT now() and updated_at (maintained by a trigger). Invaluable for debugging, syncing and audits.

Pattern 2: Soft deletes

deleted_at TIMESTAMPTZ + views/partial indexes that hide deleted rows (Unit 3)

Pattern 3: Status columns

status TEXT CHECK (status IN ('pending', 'paid', 'cancelled')) or an ENUM. Add status_changed_at if needed.

Pattern 4: Audit log / history table

Record who changed what and when: audit_log(table_name, row_id, action, old_data JSONB, new_data JSONB, changed_by, changed_at) — filled by a trigger.

Pattern 5: Lookup tables vs ENUM vs CHECK

Lookup tableENUMCHECK
Add valuesINSERT a rowALTER TYPEALTER constraint
Extra info (icon, colour)✅❌❌
Users can add values✅❌❌

Pattern 6: Polymorphic data and JSONB

For flexible per-row attributes (settings, metadata) use a JSONB column — but keep anything you filter or join on as real columns.

Pattern 7: Multi-tenant ownership

Every user-owned table gets user_id (or org_id) NOT NULL + an index + Row Level Security (Unit 14).

Example

SQL
-- Snapshot pattern: keep the price at the time of purchase
CREATE TABLE products (id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name TEXT, price NUMERIC(10,2));
CREATE TABLE order_items (
  id         INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  product_id INT REFERENCES products(id),
  qty        INT NOT NULL CHECK (qty > 0),
  unit_price NUMERIC(10,2) NOT NULL          -- copied on purpose (history)
);
INSERT INTO products (name, price) VALUES ('Water bottle', 900);
INSERT INTO order_items (product_id, qty, unit_price)
SELECT id, 2, price FROM products WHERE name = 'Water bottle';
UPDATE products SET price = 1100 WHERE name = 'Water bottle';   -- price rises later
SELECT p.name, oi.unit_price AS paid_price, p.price AS current_price
FROM order_items oi JOIN products p ON p.id = oi.product_id;     -- 900 vs 1100 ✅

-- Counter cache (denormalized) kept in sync by a trigger
ALTER TABLE users ADD COLUMN expense_count INT NOT NULL DEFAULT 0;
UPDATE users u SET expense_count = (SELECT count(*) FROM expenses e WHERE e.user_id = u.id);

CREATE FUNCTION sync_expense_count() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
  IF TG_OP = 'INSERT' THEN
    UPDATE users SET expense_count = expense_count + 1 WHERE id = NEW.user_id;
  ELSIF TG_OP = 'DELETE' THEN
    UPDATE users SET expense_count = expense_count - 1 WHERE id = OLD.user_id;
  END IF;
  RETURN NULL;
END $$;
CREATE TRIGGER expenses_count AFTER INSERT OR DELETE ON expenses
FOR EACH ROW EXECUTE FUNCTION sync_expense_count();

INSERT INTO expenses (user_id, title, amount) VALUES (5, 'First expense!', 300);
SELECT name, expense_count FROM users WHERE id = 5;              -- Maya Karki | 1

-- Lookup table with extra info (better than an ENUM here)
CREATE TABLE payment_methods (code TEXT PRIMARY KEY, label TEXT NOT NULL, icon TEXT);
INSERT INTO payment_methods VALUES ('cash', 'Cash', '💵'), ('esewa', 'eSewa', '📱'), ('card', 'Card', '💳');
ALTER TABLE expenses ADD COLUMN payment_method TEXT REFERENCES payment_methods(code) DEFAULT 'cash';