Reusable Queries with Views
Follow a view as its underlying rows change inside a transaction.
database, sql, postgresql, views, queries, abstractionGive a query a name
A view provides a named query that callers can select from. It can express a useful boundary, such as the books whose page counts are known. An ordinary PostgreSQL view is not a separately stored snapshot of its result.
SQL illustration
Use the fictional authors and books setup in the same session:
BEGIN;
CREATE TEMP VIEW known_pages AS
SELECT id, title, pages FROM books WHERE pages IS NOT NULL;
COMMIT;
SELECT id, title, pages FROM known_pages ORDER BY id;
BEGIN;
UPDATE books SET pages = 80 WHERE id = 2;
SELECT id, title, pages FROM known_pages ORDER BY id;
ROLLBACK;
SELECT id, title, pages FROM known_pages ORDER BY id;
Prepared results — not live execution:
| Before and after rollback: id | title | pages |
|---|---|---|
| 1 | Kite | 120 |
| 3 | Tide | 200 |
| 4 | Fern | 120 |
| During the transaction: id | title | pages |
|---|---|---|
| 1 | Kite | 120 |
| 2 | Oak | 80 |
| 3 | Tide | 200 |
| 4 | Fern | 120 |
Oak appears when its page count is set to 80 in the transaction, then disappears from the view again after rollback. This assumes no other session changes the data. The temporary view and tables belong to this session.
See the reasoning
Follow the example one step at a time
Follow the named query as an underlying row changes and is rolled back. This is a prepared teaching demonstration, not live code execution.
Define the view
books ── WHERE pages IS NOT NULL ──→ known_pages A named query, not a stored snapshot
The view selects books with known page counts from the underlying table.
A view is not a backup
A regular view reuses a definition; its results reflect the data visible to the querying transaction. A materialized view instead stores results and requires appropriate refresh decisions. Some simple views can be updated, subject to PostgreSQL's rules; do not assume every view is writable. Permissions, ownership, and security options still matter, and a view is not a backup or a guarantee of faster queries.
Reflect on the concept
Four fixed questions to reinforce the reasoning. Answers are not saved or scored.
