Sub topic 15
Saving a Query as a View
This chapter assumes you know basic SELECT, JOIN, WHERE, and CREATE statements, and that the book-tracking tables from earlier chapters already exist. In particular, the database has books, authors, book_authors, and readings tables.
Why use a view?
A view is a named query that you can use like a table. A regular view stores the query definition, not a separate copy of its results. When you query the view, PostgreSQL expands the view into its underlying query.
Views help when:
- A query is useful in several places.
- You want one definition of a business rule.
- You want application code to use a simpler interface.
- You want to hide unnecessary columns or joins.
For example, a finished book is a book connected to a reading entry whose status is finished. Store that rule in a view:
CREATE VIEW finished_books AS
SELECT b.book_id,
b.title,
r.finished_on,
r.rating
FROM readings AS r
JOIN books AS b USING (book_id)
WHERE r.status = 'finished';The view has four output columns. Query it as you would query a table:
SELECT title, finished_on, rating
FROM finished_books
ORDER BY finished_on;The result changes automatically when rows in books or readings change.
View design and common errors
A view should expose the columns its users need, with clear names. Avoid SELECT *. If the base table gains a column later, SELECT * can change the view's output unexpectedly and break consumers.
A view usually cannot replace all table rules. It presents data, but it does not automatically prevent invalid writes to the underlying tables. Keep validation in NOT NULL, UNIQUE, CHECK, and foreign-key constraints.
You can inspect a view's definition with PostgreSQL's catalog:
SELECT pg_get_viewdef('finished_books'::regclass, true);If the definition needs to change, replace it explicitly:
CREATE OR REPLACE VIEW finished_books AS
SELECT b.book_id,
b.title,
r.finished_on,
r.rating
FROM readings AS r
JOIN books AS b USING (book_id)
WHERE r.status = 'finished'
AND r.finished_on IS NOT NULL;The added condition excludes incomplete rows that happen to have status finished but no completion date. Whether this rule belongs in the view or in a table constraint depends on the domain. If every finished reading must have a date, a constraint is stronger because it protects the data for every query.
A view can also simplify permissions. You can grant access to the view without granting access to every column in the base tables. Check your PostgreSQL version and permission design before relying on this pattern.
Exercise
What happens to finished_books when a matching reading changes from finished to reading?
Show answer
The row no longer appears in the view because PostgreSQL evaluates the view's query when it is read.