1 Understanding and Creating Views
TopA view is a saved query that acts like a virtual table. It doesn't store data itself — it runs the underlying query every time you access it. Think of it as a bookmark for a complex query that you can reuse by name.
Why Use Views?
- Simplify complex queries — write a 20-line JOIN once, then
SELECT * FROM my_view - Security — expose only certain columns to certain users (hide salary, SSN, etc.)
- Consistency — everyone in the team uses the same query logic
- Abstraction — change the underlying tables without breaking application code
Creating a View
-- A view that shows order details with customer names
CREATE VIEW order_details AS
SELECT
c.name AS customer,
c.city,
o.product,
o.amount,
o.order_date,
o.amount * o.quantity AS total
FROM customers c
JOIN orders o ON c.id = o.customer_id;Now use it exactly like a table:
-- Simple and clean — no need to remember the JOIN
SELECT customer, product, total
FROM order_details
WHERE total > 100
ORDER BY total DESC;Modifying and Dropping Views
-- Replace with an updated definition
CREATE OR REPLACE VIEW order_details AS
SELECT c.name AS customer, o.product, o.amount
FROM customers c
JOIN orders o ON c.id = o.customer_id;
-- Delete a view
DROP VIEW IF EXISTS order_details;View Limitations
| Can Do | Can't Do (Usually) |
|---|---|
| SELECT, WHERE, ORDER BY, GROUP BY | INSERT/UPDATE/DELETE on views with JOINs |
| Join multiple tables | Use variables or parameters (use procedures instead) |
| Nest views (view of a view) | Index a view directly (MySQL) |
Performance note: Views don't cache results — the underlying query runs every time. A view on a complex 5-table JOIN will be just as slow as running that JOIN directly. For performance-critical queries, consider materialized views (PostgreSQL) or creating summary tables.
Key Takeaways
- A view is a saved SELECT query that behaves like a virtual table
-
CREATE VIEW name AS SELECT ...— thenSELECT * FROM name - Use views to simplify complex queries, enforce security, and ensure consistency
- Views don't store data or improve performance — the query runs each time