MySQL Views
MySQL Views: Saved Virtual Tables for Reusable Queries
A MySQL view is a saved SELECT query stored inside the database that you can query just like a regular table. Views do not store duplicate row data on disk—every time you query a view, MySQL runs its underlying SELECT statement against the live base tables.
Basic Syntax
Use CREATE OR REPLACE VIEW so migrations update existing views cleanly without dropping permissions:
CREATE OR REPLACE VIEW view_name AS
SELECT col1, col2
FROM table_name
WHERE condition;
You query a view using standard SELECT ... FROM view_name; and remove it with DROP VIEW IF EXISTS view_name;.
Practical SQL Example
This view exposes a sanitized customer summary from demo_customers and demo_orders, hiding private contact columns from analytics dashboards:
CREATE OR REPLACE VIEW demo_customer_summary_view AS
SELECT
c.id AS customer_id,
c.first_name,
c.city,
COUNT(o.id) AS total_orders,
COALESCE(SUM(o.total_amount), 0.00) AS total_spent
FROM demo_customers AS c
LEFT JOIN demo_orders AS o
ON o.customer_id = c.id
AND o.status = 'paid'
GROUP BY c.id, c.first_name, c.city;
-- Query the view like a normal table
SELECT customer_id, first_name, total_orders, total_spent
FROM demo_customer_summary_view
WHERE total_spent >= 100.00;
Common Mistakes and Best Practices
- Do Not Mistake Views for Materialized Caches: Standard MySQL views execute the underlying joins on every query. If a view wraps heavy aggregations, add proper indexes on the base tables or build a summary table refreshed on a schedule.
- Avoid Stacking Views Inside Views: Nesting three or four layers of views hides expensive joins and often prevents the optimizer from pushing
WHEREpredicates down cleanly. - Know When Views Are Read-Only: Views using
GROUP BY,DISTINCT,UNION, or aggregate functions cannot be updated withINSERTorUPDATE.
Frequently Asked Questions
Do MySQL views take up extra disk space for rows?
No, a standard MySQL view stores only its SQL definition—row data stays exclusively in the underlying base tables.
Can views restrict user access to sensitive columns?
Yes, you can grant SELECT on a view that omits columns like password_hash while denying direct access to the base table.
Does MySQL support materialized views natively?
No, unlike PostgreSQL or Oracle, MySQL has no built-in MATERIALIZED VIEW keyword; teams simulate them with summary tables updated via scheduled events or jobs.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.