advanced
Views
Save a query as a named, reusable virtual table with CREATE VIEW.
5 min read
Explanation
A view is a saved query that behaves like a virtual table. Instead of
retyping a complex SELECT everywhere, you store it once with CREATE VIEW and
then SELECT from the view by name.
Views are great for:
- Hiding complexity behind a friendly name
- Enforcing a consistent "official" definition of a report
- Restricting columns for security (expose only some columns)
Importantly, a normal view stores no data — it re-runs its underlying query every time you use it.
Views compose
You can build a view on top of other views. Just keep an eye on performance, since each layer re-executes its query.
Syntax
CREATE VIEW view_name AS
SELECT col1, col2
FROM table
WHERE condition;
SELECT * FROM view_name;Interactive Example
Create a view of high earners, then query it. Then create a department-summary view and aggregate over it.
Loading database engine...
Loading database engine...
Common Mistakes
- Assuming a view caches data. A regular view recomputes on every use; for heavy queries consider a materialized view or a real table.
- Expecting updates to work. Many views are read-only; don't design writes through them.
- Naming collisions. Give views clear, distinct names so they don't clash with tables.
Best Practices
- Use views to standardize repeated report logic across your team.
- Keep view definitions focused; compose small views into bigger ones.
- Drop and recreate (
CREATE OR REPLACE VIEW) when the underlying logic changes.
Practice Question
Create a view called senior_engineers containing employees in department 1
hired before 2020, then SELECT their names ordered by salary.
Summary
A view is a named, reusable query treated like a table. It simplifies complex queries and standardizes reports, but a standard view holds no data and often isn't updatable.