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 customersEncapsulate 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 builtFast 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.
