Sub topic 15
Saving a query as a view
This chapter assumes you have the books, authors, book_authors, and readings tables from the earlier chapters, and that you can write joins and GROUP BY queries. You will turn the finished-books query into a view, then look at how views behave: what they store, how to change them, when they can be written to, and who can read through them.
What a view is
A view is a named SELECT statement stored in the database catalog. It holds no rows of its own. Each time you query the view, PostgreSQL substitutes the stored query into yours and plans the combined result. This substitution is done by the rewrite system, and the plan is built from the underlying tables.
Two consequences follow:
- A view is always current. New rows in
readingsappear in the view immediately. - A view does not make a query faster. It makes the query shorter to write and consistent across users.
Creating the finished-books view
The join between readings and books filtered to finished entries is one you will write often. Name it once:
CREATE VIEW finished_books AS
SELECT b.book_id, b.title, r.finished_on, r.rating
FROM readings r
JOIN books b USING (book_id)
WHERE r.status = 'finished';Now it reads like a table:
SELECT title, finished_on, rating
FROM finished_books
WHERE finished_on >= date '2025-01-01'
ORDER BY finished_on DESC;Your WHERE clause is combined with the view's WHERE r.status = 'finished'. The planner can push the date filter down to readings and use an index on it, if one exists. The indexes from the earlier chapter, such as readings_book_id_idx, still apply, because the view is expanded before planning.
You can see what PostgreSQL stored with:
SELECT pg_get_viewdef('finished_books'::regclass, true);In psql, \d+ finished_books shows the columns and the definition together.
Do not put ORDER BY in the definition
It is tempting to add ORDER BY finished_on DESC to the view. Avoid it. The ordering is applied only when the view is queried directly with no other ordering, and it forces a sort even when the caller does not need one. Let each caller sort. The exception is a view that uses LIMIT, where the order decides which rows are kept.
Views on views
A view can read from another view. This is useful for summaries. The yearly summary from the aggregation chapter can sit on top of finished_books:
CREATE VIEW yearly_reading AS
SELECT extract(year FROM finished_on)::int AS year,
count(*) AS books_finished,
round(avg(rating), 2) AS avg_rating
FROM finished_books
WHERE finished_on IS NOT NULL
GROUP BY 1;Querying yearly_reading expands both layers. Keep stacks shallow. Each layer hides some of the cost, and a three-deep stack is hard to debug in EXPLAIN output.
Changing a view
PostgreSQL gives you several ways to change a view. Which one applies depends on what you want to change.
| Change | Command | Notes |
|---|---|---|
| Add a column at the end | `CREATE OR REPLACE VIEW` | Existing columns must keep their names, types, and order. |
| Rename a column | `ALTER VIEW ... RENAME COLUMN` | Does not rewrite the query. |
| Reorder, remove, or retype columns | `DROP VIEW` then `CREATE VIEW` | Fails if other objects depend on it, unless you use `CASCADE`. |
| Rename the view | `ALTER VIEW ... RENAME TO` | Dependent views keep working because they reference the view by OID. |
Adding started_on to the end of the column list is allowed:
CREATE OR REPLACE VIEW finished_books AS
SELECT b.book_id, b.title, r.finished_on, r.rating, r.started_on
FROM readings r
JOIN books b USING (book_id)
WHERE r.status = 'finished';Putting started_on in the middle would fail, because PostgreSQL would read it as a rename and retype of the column that used to be in that position.
Dropping a base table column that a view uses fails with a dependency error. This protects you, but it also means that schema changes must account for views. DROP ... CASCADE removes the dependent views as well. Read the notice before you use it.
Writing through a view
A simple view can accept INSERT, UPDATE, and DELETE, and PostgreSQL applies them to the single base table. A view qualifies when it reads from one table and has no joins, DISTINCT, GROUP BY, aggregates, or set operations. finished_books joins two tables, so it is read-only.
A single-table view works. Add WITH CHECK OPTION so that writes cannot create rows the view would not show:
CREATE VIEW current_reads AS
SELECT reading_id, book_id, started_on
FROM readings
WHERE status = 'reading'
WITH CHECK OPTION;
-- Allowed: the row still satisfies status = 'reading'
UPDATE current_reads SET started_on = current_date WHERE reading_id = 1;
-- Rejected: status is not in the view, so the new row gets the default
-- 'want_to_read', which fails the view's WHERE clause
INSERT INTO current_reads (book_id) VALUES (1);The insert fails with new row violates check option for view "current_reads". Without WITH CHECK OPTION, the insert would succeed, and the new row would be invisible through the view. The check constraints on readings still apply to every write, including writes through a view.
For a join view that you need to write to, the options are INSTEAD OF triggers or writing to the base tables directly. In most applications, writing to the tables is simpler.
Permissions and security
By default a view runs with the privileges of its owner, not of the user who queries it. Granting SELECT on a view therefore exposes the underlying rows the view selects, even if the user has no access to the tables:
CREATE ROLE report_reader;
GRANT SELECT ON finished_books TO report_reader;This makes views a simple way to expose a limited set of columns and rows. The same property has a catch: row-level security policies on the base tables are checked against the view owner, so they may not filter what the caller sees. In PostgreSQL 15 and newer you can change this:
ALTER VIEW finished_books SET (security_invoker = true);With security_invoker, permissions and row-level security on the base tables are checked as the calling user. The setting does not exist in PostgreSQL 12 to 14, so on those versions use a separate owner role and grant carefully.
Materialized views
If a summary is expensive and a stale answer is acceptable, a materialized view stores the result on disk. It is a snapshot that you refresh on demand:
CREATE MATERIALIZED VIEW yearly_reading_snapshot AS
SELECT year, books_finished, avg_rating
FROM yearly_reading;
CREATE UNIQUE INDEX yearly_reading_snapshot_year_idx
ON yearly_reading_snapshot (year);
REFRESH MATERIALIZED VIEW CONCURRENTLY yearly_reading_snapshot;CONCURRENTLY lets readers keep querying during the refresh, but it requires a unique index on the materialized view. A plain refresh locks out readers while it runs. The data is only as fresh as the last refresh, and no trigger does this for you. Use a scheduled job or call it after bulk loads. For a personal reading log, a normal view is almost always enough.
Checking the plan
A view does not appear in a query plan. EXPLAIN shows the tables behind it:
EXPLAIN
SELECT title FROM finished_books WHERE rating = 5;You will see scans on readings and books with both filters applied. If the plan is slow, add indexes to the base tables, not to the view. An exception is the materialized view above, which can have its own indexes.
Common mistakes
- Expecting a view to cache results. A normal view runs its query every time.
- Using
SELECT *in the definition and then being surprised by missing columns. - Dropping and recreating a view, which loses its grants and makes dependent views fail. Prefer
CREATE OR REPLACE VIEWwhen only adding columns. - Assuming the finished-books view has one row per book. A book read twice has two finished readings and so appears twice. Group by
book_idif you need one row per book.
Exercise
You create CREATE VIEW current_reads AS SELECT reading_id, book_id FROM readings WHERE status = 'reading' with no WITH CHECK OPTION. A colleague runs INSERT INTO current_reads (book_id) VALUES (7). Does the insert succeed, what status does the new row have, and will the row appear in current_reads?
Show answer
The insert succeeds, because the view is a simple single-table view and is automatically updatable. The status column is not in the view, so the new row takes the column default, want_to_read. That does not match status = 'reading', so the row does not appear in current_reads. Adding WITH CHECK OPTION makes the insert fail instead.
Exercise
You want to add the page_count column from books to finished_books. Which statement do you use, and where must the column go in the select list?
Show answer
Use CREATE OR REPLACE VIEW finished_books AS ... with b.page_count added at the end of the select list, after the existing columns. Existing columns must keep their names, types, and order, so a column inserted in the middle is rejected.