SQL · Module 07: Schema Design, Normalization & ViewsTutorial 20 of 24

7.2 Views vs Materialized Views, Triggers & Stored Procedures

Compare regular Views vs Materialized Views (real-time vs cached speed), understand when Triggers help or hurt, and learn how Stored Procedures encapsulate reusable database logic.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

1. Regular VIEW vs MATERIALIZED VIEW (Crucial Difference!)

A VIEW is a saved SELECT query that behaves like a virtual table. A MATERIALIZED VIEW actually stores the query's computed rows on disk like a cached snapshot!

FeatureRegular VIEWMATERIALIZED VIEW (PostgreSQL / Oracle)
Stores Data on Disk?❌ No — just saves the SQL query text✅ Yes — caches the physical result rows on disk
Data Freshness✅ Always 100% real-time (re-runs underlying query on every read)⚠️ Can be stale until you run REFRESH MATERIALIZED VIEW
Read Speed on Heavy JoinsSame cost as running the underlying query✅ Instant (O(1) / indexed reads!)
Can Add Indexes?❌ No✅ Yes! You can index a Materialized View!
Best Used ForHiding sensitive columns (password_hash), simplifying complex joinsHeavy executive analytics dashboards refreshed every 15 mins / nightly
SQL
-- 1. Regular View: Safe public profile (hides password_hash & phone from analysts!)
CREATE OR REPLACE VIEW public_users AS
SELECT user_id, name, role, created_at
FROM users
WHERE is_active = TRUE;

-- Query it just like a normal table:
SELECT * FROM public_users WHERE role = 'learner';
SQL
-- 2. Materialized View: Pre-computed daily revenue dashboard (PostgreSQL)
CREATE MATERIALIZED VIEW mv_daily_revenue AS
SELECT
    DATE(created_at) AS sale_day,
    COUNT(*)         AS paid_orders,
    SUM(amount)      AS total_revenue
FROM orders
WHERE status = 'paid'
GROUP BY DATE(created_at);

-- Add a unique index so we can refresh WITHOUT locking readers!
CREATE UNIQUE INDEX idx_mv_daily_rev_day ON mv_daily_revenue (sale_day);

-- Refresh on a cron schedule without blocking dashboard reads:
REFRESH MATERIALIZED VIEW CONCURRENTLY mv_daily_revenue;

2. Triggers & Stored Procedures — When to Use (and Avoid!)

Triggers (Automatic Side-Effects on INSERT / UPDATE / DELETE)

A Trigger runs a function automatically whenever a row changes — e.g., auto-updating updated_at = NOW() or writing an immutable audit log:

SQL
-- PostgreSQL Trigger: Automatically keep updated_at fresh on every UPDATE
CREATE OR REPLACE FUNCTION set_updated_at()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = CURRENT_TIMESTAMP;
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER trg_users_updated_at
BEFORE UPDATE ON users
FOR EACH ROW
EXECUTE FUNCTION set_updated_at();

Stored Procedures vs Application Code (Architecture Trade-Off)

  • Good uses for DB Triggers/Procedures: updated_at timestamps, strict audit trails, atomic ledger balance transfers.
  • Avoid putting complex business logic in Triggers: They are invisible when reading backend code (Node/Python/Java), harder to unit-test, and can cause hidden cascading performance bottlenecks!

3. Quick Check Your Understanding

Module 7.2 Quick Quiz

Q1.What is the main difference between a regular VIEW and a MATERIALIZED VIEW?
Q2.Why is REFRESH MATERIALIZED VIEW CONCURRENTLY preferred in production PostgreSQL?

Keep Exploring: Related Lessons & Tools

All Courses →