CREATE VIEW: reusable query interfaces
Overview
A view is a named query that applications can read like a relation. Ordinary views do not persist their result rows. Use CREATE VIEW name AS SELECT ... to expose a stable projection or reusable filter; each query sees data according to its transaction snapshot. The catalog fixture contains three products, two active. Run every example in a fresh disposable database.
First example
SELECT id,name,price FROM vw_active ORDER BY id;Observed SQLite result (rows in JSON):
[ [ 1, "Pen", 100 ], [ 2, "Paper", 200 ]]How it works
The first query reads a projection of active products. The second adds a nested view inside a transaction, modifies a base value and observes the change through the nested view before rolling everything back. Give columns explicit names and order the outer SELECT. In PostgreSQL 17 CREATE OR REPLACE VIEW can append columns but must retain existing column names, order and types; ALTER VIEW changes supported properties and DROP VIEW removes the definition. Check dependent objects before replacing or dropping views. The optimizer may simplify view queries; a view is not automatically faster than the underlying query.
Practical example
BEGIN;CREATE VIEW vw_budget AS SELECT id,price FROM vw_active WHERE price<=150;UPDATE vw_product SET price=140 WHERE id=1;SELECT id,price FROM vw_budget ORDER BY id;ROLLBACK;Observed SQLite result (rows in JSON):
[ [ 1, 140 ]]Practice and mistakes
Practice: create a view exposing only active products with price at least 100; read it ordered by id, then change product 1 to 90 and read it again. Hint 1: combine predicates with AND. Hint 2: roll back the change. Expect product 1 to disappear after the update. Mistake: treating a view as a permanent copy or assuming ordering without ORDER BY.