Views: Saving a Query With a Name
Sometimes you write the same SELECT again and again, perhaps a join of three tables or a filtered list. A view lets you save that query under a name and then use it as if it were a table. This page introduces views gently.
Creating a view
CREATE VIEW paid_orders AS
SELECT o.id, c.name AS customer, o.total_cents, o.created_at
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.status = 'paid';
Using it
SELECT customer, total_cents
FROM paid_orders
ORDER BY created_at DESC
LIMIT 10;
You query paid_orders just like a table. Each time, the database runs the saved query underneath and gives you the current results.
What a view is, and is not
- A view stores the query, not a copy of the data. When orders change, the view shows the change straight away.
- A view has no rows of its own in the usual case. Some databases also offer *materialised* views, which do store a copy and must be refreshed; those are a more advanced topic.
Why views are useful
| Benefit | Example |
|---|---|
| Readability | Hide a long join behind a clear name like paid_orders |
| Consistency | Everyone uses the same definition of "paid" |
| Permissions | Let a reporting user read the view but not the full tables (in server databases) |
| Simpler app code | The app queries one name instead of repeating a join |
Changing or removing a view
DROP VIEW paid_orders;
Then create it again with the new definition. PostgreSQL and MySQL also support CREATE OR REPLACE VIEW for many changes; SQLite needs DROP and CREATE.
Limits to know
- Inserting through views is possible in some databases for simple views, but rules vary. As a beginner, treat views as read-only.
- Performance: a view is only as fast as the query inside it. Wrapping a slow query in a view does not make it faster.
- Views on views can become hard to follow. Keep them shallow.
A good first view to make
Take a join you have written more than twice in your practice project, such as books with their authors, and turn it into a view:
CREATE VIEW books_with_authors AS
SELECT b.id, b.title, a.name AS author
FROM books b
JOIN authors a ON a.id = b.author_id;
Then rewrite your other queries to use it, and see how much shorter they become.
Where next
Views pair well with subqueries and CTEs, which also help break complicated questions into named steps. For the join inside most views, see INNER and LEFT JOIN, one small step at a time.
A free learning page for beginners. Practise on a test database, never on real customer data, and check the official documentation for your database version.