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

Why views are useful

BenefitExample
ReadabilityHide a long join behind a clear name like paid_orders
ConsistencyEveryone uses the same definition of "paid"
PermissionsLet a reporting user read the view but not the full tables (in server databases)
Simpler app codeThe 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

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.

Related pages on this site