SQL Views
A view is a saved query that you can use like a virtual table. It does not usually store its own copy of the data; it reads from the underlying tables when queried.
Why use a view?
- Hide complex joins behind a simpler name.
- Expose only selected columns to users or reports.
- Reuse a query in many places.
- Make reporting queries easier to read.
Syntax
CREATE VIEW view_name AS
SELECT column1, column2
FROM table_name
WHERE condition;
Example
Create a view with active customers:
CREATE VIEW active_customers AS
SELECT customer_id, customer_name, email
FROM customers
WHERE status = 'active';
Then query the view:
SELECT customer_name, email
FROM active_customers
ORDER BY customer_name;
Common mistakes
- Assuming a view is always a physical table.
- Changing underlying tables without checking the views that depend on them.
- Putting too much hidden logic in views without documenting it.
Related topics
See also SQL CREATE VIEW, SQL SELECT and the SQL Formatter.