PostgreSQL Views
A view is a saved query with a name. You query it like a table, but it stores no data of its own: every time you select from it, PostgreSQL runs the underlying query. Views hide complexity, give everyone the same definitions ("what is revenue?"), and can limit which columns users see.
Creating a view
The join between books, authors and categories appears in many reports. Let's save it once:
CREATE VIEW book_catalog AS
SELECT b.id, b.title, a.name AS author, c.name AS category, b.price, b.stock
FROM books b
JOIN authors a ON a.id = b.author_id
JOIN categories c ON c.id = b.category_id;
SELECT title, author, price
FROM book_catalog
WHERE category = 'Mystery'
ORDER BY price;CREATE VIEW
title | author | price
--------------------+--------------+-------
Murder at Low Tide | Daniel Reyes | 11.99
The Map Thief | Daniel Reyes | 12.99
The Quiet Witness | Daniel Reyes | 13.49
(3 rows)
You can filter, sort, join and aggregate a view exactly like a table:
CREATE VIEW book_catalog AS
SELECT b.id, b.title, a.name AS author, c.name AS category, b.price, b.stock
FROM books b
JOIN authors a ON a.id = b.author_id
JOIN categories c ON c.id = b.category_id;
SELECT category, count(*) AS titles, sum(stock) AS copies
FROM book_catalog
GROUP BY category
ORDER BY category;CREATE VIEW
category | titles | copies
-----------------+--------+--------
Children | 2 | 55
Fiction | 5 | 31
History | 3 | 8
Mystery | 3 | 39
Programming | 4 | 30
Science Fiction | 3 | 25
(6 rows)
Views are always up to date
Because a view is just a query, it sees changes to its tables immediately:
CREATE VIEW low_stock AS
SELECT title, stock FROM books WHERE stock BETWEEN 1 AND 3;
SELECT * FROM low_stock ORDER BY stock;
UPDATE books SET stock = 2 WHERE title = 'Postgres in Practice';
SELECT * FROM low_stock ORDER BY stock, title;CREATE VIEW
title | stock
-----------------+-------
Winter in Sofia | 1
Empires of Sand | 2
The Last Orbit | 3
(3 rows)
UPDATE 1
title | stock
----------------------+-------
Winter in Sofia | 1
Empires of Sand | 2
Postgres in Practice | 2
The Last Orbit | 3
(4 rows)
Replacing and dropping views
CREATE OR REPLACE VIEW redefines a view (you may add columns at the end, but not remove or rename existing ones). DROP VIEW removes it; the tables are untouched.
CREATE VIEW customer_names AS SELECT id, first_name FROM customers;
CREATE OR REPLACE VIEW customer_names AS
SELECT id, first_name, first_name || ' ' || last_name AS full_name FROM customers;
SELECT * FROM customer_names WHERE id <= 2;
DROP VIEW customer_names;CREATE VIEW
CREATE VIEW
id | first_name | full_name
----+------------+---------------
1 | Anna | Anna Kowalski
2 | Ben | Ben Carter
(2 rows)
DROP VIEW
Updatable views
A simple view over one table (no joins, aggregates or DISTINCT) is automatically updatable: inserts and updates go through to the base table. WITH CHECK OPTION refuses changes that would make the row disappear from the view:
CREATE VIEW uk_customers AS
SELECT id, first_name, last_name, city, country, joined
FROM customers WHERE country = 'UK'
WITH CHECK OPTION;
UPDATE uk_customers SET city = 'York' WHERE first_name = 'Isla';
INSERT INTO uk_customers (first_name, last_name, city, country, joined)
VALUES ('Paolo', 'Ricci', 'Rome', 'Italy', '2025-01-01');
SELECT first_name, city FROM uk_customers ORDER BY first_name;CREATE VIEW
UPDATE 1
ERROR: new row violates check option for view "uk_customers"
DETAIL: Failing row contains (16, Paolo, Ricci, null, Rome, Italy, 2025-01-01).
first_name | city
------------+-------
Ben | Leeds
Isla | York
Olivia | Leeds
(3 rows)
Materialized views
A materialized view stores the result of its query, like a snapshot. Reading it is as fast as reading a table, which is great for expensive reports, but it does not update by itself; you run REFRESH MATERIALIZED VIEW when you want fresh data:
CREATE MATERIALIZED VIEW sales_by_book AS
SELECT b.title, sum(oi.quantity) AS copies
FROM order_items oi JOIN books b ON b.id = oi.book_id
GROUP BY b.title;
SELECT * FROM sales_by_book WHERE title = 'Moon Socks';
INSERT INTO order_items (order_id, book_id, quantity, unit_price) VALUES (1, 14, 10, 7.50);
SELECT * FROM sales_by_book WHERE title = 'Moon Socks';
REFRESH MATERIALIZED VIEW sales_by_book;
SELECT * FROM sales_by_book WHERE title = 'Moon Socks';SELECT 17
title | copies
------------+--------
Moon Socks | 5
(1 row)
INSERT 0 1
title | copies
------------+--------
Moon Socks | 5
(1 row)
REFRESH MATERIALIZED VIEW
title | copies
------------+--------
Moon Socks | 15
(1 row)
| View | Materialized view | |
|---|---|---|
| Stores data | no | yes |
| Always current | yes | only after REFRESH |
| Speed | as fast as its query | as fast as a table; can be indexed |
| Typical use | reuse, security, simplification | dashboards, heavy reports |
Tip: To list the views in a database without psql's
\dv, queryinformation_schema.views(orpg_matviewsfor materialized views).
Test yourself
Does a regular view store a copy of the data?
- Yes, it is refreshed every hour
- No, it runs its query each time it is used
- Only the first time
- Only for joins
How do you update the data in a materialized view?
- UPDATE VIEW
- It updates automatically
- REFRESH MATERIALIZED VIEW name
- DROP and CREATE are the only way
What does WITH CHECK OPTION do on an updatable view?
- Checks permissions
- Rejects inserts/updates that would produce rows not visible through the view
- Validates the SQL syntax
- Makes the view read-only