SQL Practice Logo

SQLPractice Online

Denormalization Strategies: Functions

Module: Schema Design & Advanced DDL

## Adding Redundant Columns

```sql

-- Step 1: Add the redundant column

ALTER TABLE orders

ADD COLUMN customer_name VARCHAR(100);

-- Step 2: Populate existing data

UPDATE orders o

SET customer_name = (

SELECT name FROM customers c WHERE c.customer_id = o.customer_id

);

-- Step 3: Create trigger to maintain consistency

CREATE TRIGGER sync_customer_name

AFTER UPDATE OF name ON customers

FOR EACH ROW

BEGIN

UPDATE orders

SET customer_name = NEW.name

WHERE customer_id = NEW.customer_id;

END;

-- Step 4: Update application code to set customer_name on INSERT

INSERT INTO orders (customer_id, customer_name, total)

SELECT customer_id, name, 100.00

FROM customers

WHERE customer_id = 123;

```

## Creating Pre-Aggregated Tables

```sql

-- Step 1: Create the summary table

CREATE TABLE user_order_stats (

user_id INT PRIMARY KEY,

total_orders INT DEFAULT 0,

total_spent DECIMAL(10,2) DEFAULT 0,

last_order_date DATE,

updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP

);

-- Step 2: Populate initial data

INSERT INTO user_order_stats (user_id, total_orders, total_spent, last_order_date)

SELECT

customer_id,

COUNT(*),