Part 13 / Topic 1 of 8
Views
A view is a saved query wearing a table costume. Part 5's "order details" query, used everywhere? Name it once:
CREATE VIEW order_details AS
SELECT o.order_id, o.order_date, o.status,
c.first_name, p.name AS product,
oi.quantity, oi.unit_price,
oi.quantity * oi.unit_price AS line_total
FROM order_items AS oi
JOIN orders AS o ON o.order_id = oi.order_id
JOIN customers AS c ON c.customer_id = o.customer_id
JOIN products AS p ON p.product_id = oi.product_id;
SELECT first_name, product, line_total
FROM order_details
WHERE order_id = 1;
CREATE VIEW
first_name | product | line_total
------------+-------------------+------------
Asha | Laptop Pro 14 | 1200.00
Asha | SQL for Beginners | 70.00
(2 rows)
The view stores no data — each query against it runs the underlying SELECT with your conditions folded in. That makes views free abstraction: the four-table join is written once, reviewed once, and every report speaks order_details. They also make fine security fences: grant access to a view exposing only safe columns, not to the raw table (Stage 5's backend track runs with this).
Simple single-table views are automatically updatable — UPDATE/INSERT against the view writes through to the table. Views with joins or aggregates (like ours) are read-only, which is usually exactly right.
🧪 Quick quiz — answer from memory, then check.
- How much data does a view store?
- Which views can you write through?
Show the answers
- None — it's a named query, executed fresh each use.
- Simple ones (single table, no aggregates/DISTINCT/joins); anything fancier is read-only without extra machinery.
Done here? The practice set for Part 13 — 6 exercises with solutions — is on the part page.