SQL ยท Chapter 36 of 42

SQL Views

A VIEW is a saved SELECT query that behaves like a virtual table. Simplifies complex queries and hides implementation details.

A MATERIALIZED VIEW stores the result โ€” much faster to read but needs periodic refresh.

Example 1 (sql)
CREATE VIEW top_customers AS
SELECT user_id, SUM(total) AS spent
FROM orders GROUP BY user_id
ORDER BY spent DESC;

SELECT * FROM top_customers LIMIT 10;
Output
Top 10 customers

Encapsulate a common aggregation.

Example 2 (sql)
CREATE MATERIALIZED VIEW daily_sales AS
SELECT DATE(created_at) AS day, SUM(total) AS revenue
FROM orders GROUP BY 1;
Output
Materialized view built

Fast dashboard queries โ€” refresh with REFRESH MATERIALIZED VIEW.

Key points

  • Regular view = saved query.
  • Materialized view = stored result.
  • Great for security (expose only certain columns).
  • Refresh materialized views to keep data fresh.
๐Ÿ’ก Note: MySQL didn't support materialized views natively for a long time โ€” check your DB's docs.

๐Ÿ“ Quick Quiz

1. A regular view stores:

2. A materialized view stores:

3. Materialized views need to be: