✏️ Explanatory Question

What is the difference between a view and a materialized view?

👁 10 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

71

What is the difference between a view and a materialized view?

Level: Advanced — A "gotcha" question, since MySQL does not natively support materialized views.

The key difference is whether the result is stored physically:

  • View (Virtual): Stores only the query definition. Every time you query it, the underlying SELECT runs and returns live, always-current data.
  • Materialized View: Stores the actual result set physically on disk. Reads are very fast, but the data is a snapshot that must be refreshed to stay current.
Important — MySQL note: MySQL does NOT natively support materialized views (unlike PostgreSQL or Oracle). Developers simulate them using a regular table + scheduled event/trigger that periodically refreshes the data.

Side-by-Side Comparison

Feature View Materialized View
Stores data? No (definition only) Yes (physical result)
Data freshness Always current (live) Snapshot (needs refresh)
Read speed Slower (runs query) Very fast (precomputed)
Storage cost Minimal Full result stored
Best for Real-time data Expensive aggregations / reports
MySQL support Native Not native (simulated)

Quick Example — Simulating a Materialized View in MySQL

-- 1) Create a real table to hold the precomputed results
CREATE TABLE mv_dept_summary (
    dept_id     INT,
    dept_name   VARCHAR(50),
    emp_count   INT,
    avg_salary  DECIMAL(10,2),
    refreshed_at DATETIME
);

-- 2) A procedure to (re)populate it
DELIMITER $$
CREATE PROCEDURE RefreshDeptSummary()
BEGIN
    TRUNCATE TABLE mv_dept_summary;
    INSERT INTO mv_dept_summary
    SELECT d.dept_id, d.dept_name, COUNT(e.emp_id),
           AVG(e.salary), NOW()
    FROM departments d
    LEFT JOIN employees e ON d.dept_id = e.dept_id
    GROUP BY d.dept_id, d.dept_name;
END $$
DELIMITER ;

-- 3) Schedule an automatic refresh with an EVENT (e.g., hourly)
CREATE EVENT ev_refresh_summary
ON SCHEDULE EVERY 1 HOUR
DO CALL RefreshDeptSummary();

-- Now reads are instant (no heavy aggregation each time)
SELECT * FROM mv_dept_summary;
Interviewer tip: The one-liner they want — "A view stores only the query and returns live data, while a materialized view stores the physical result for fast reads but needs refreshing. MySQL has no native materialized views — they're simulated with a table plus a scheduled event."