Question presented to candidate: "What is a view, what is a materialized view, and how do you decide which one to use? What happens to each when the underlying table changes?"
What a strong answer should cover:
- A view is a saved, named query: it stores no rows, and every query against it runs the definition again, so it is always current; the planner inlines it into the outer query
- A materialized view stores the result rows on disk like a table: reads are as fast as reading a small table, but the data is a snapshot that is stale until
REFRESH MATERIALIZED VIEW - Uses: views for reuse, simpler queries, a stable interface and column-level security; materialized views for expensive aggregates read far more often than the data changes (dashboards, reports)
- Refresh behaviour in PostgreSQL: a plain refresh blocks readers;
CONCURRENTLY(9.4+) lets reads continue but needs a unique index; there is no built-in automatic or incremental refresh - Engine differences: SQLite and MySQL have views but no materialized views; SQL Server has indexed views; simple views can be updatable, aggregate views are not
Code / implementation expected: Optional β CREATE VIEW, CREATE MATERIALIZED VIEW, REFRESH, and a demonstration that one is live and the other is a snapshot.
Schema used by the examples: