SQL Tutorial · Changing Data and Tables · Lesson 33 of 36

SQL Views

Save a query as a virtual table with CREATE VIEW.

CREATE VIEW

A view is a saved query you can select from like a table. It always shows current data, because the query runs each time:

Example 1Try it yourself
CREATE VIEW order_summary AS
SELECT o.order_id, c.name AS customer, o.status,
       ROUND(SUM(oi.quantity * oi.unit_price), 2) AS total
FROM orders o
JOIN customers c ON c.customer_id = o.customer_id
JOIN order_items oi ON oi.order_id = o.order_id
GROUP BY o.order_id;

SELECT * FROM order_summary WHERE status = 'delivered' ORDER BY total DESC LIMIT 3;

Output

order_id | customer | status | total
7 | Grace Hopper | delivered | 114.99
5 | Linus Torvalds | delivered | 114.98
2 | Alan Turing | delivered | 113.99

Views simplify complex queries, give reports a stable interface, and can limit which columns users see. PostgreSQL also has materialized views that store the result and are refreshed on demand — useful for expensive reports.

Test yourself

Does a regular view store a copy of the data?

  1. Yes
  2. No — it runs its query each time
Show answer

Answer: No — it runs its query each time