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.
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!
| Feature | Regular VIEW | MATERIALIZED 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 Joins | Same cost as running the underlying query | ✅ Instant (O(1) / indexed reads!) |
| Can Add Indexes? | ❌ No | ✅ Yes! You can index a Materialized View! |
| Best Used For | Hiding sensitive columns (password_hash), simplifying complex joins | Heavy executive analytics dashboards refreshed every 15 mins / nightly |
-- 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';
-- 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:
-- 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_attimestamps, 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
Keep Exploring: Related Lessons & Tools
All Courses →Compare two versions of text, source code, config files, or JSON payloads side-by-side using exact LCS diffing with recursive JSON key sorting and patch export.
Compute MD5, SHA-1, SHA-256, SHA-384, and SHA-512 hashes or keyed HMAC signatures directly in your browser using Web Crypto.