Views
SELECT query that behaves like a virtual table. It doesn't store any data of its own — every time you query the view, PostgreSQL runs the underlying query fresh and hands you the result, as if you'd typed the whole query yourself.Creating a view
Create a view
CREATE VIEW active_customers AS SELECT id, name, email, signup_date FROM customers WHERE status = 'active';
active_customers can be queried exactly like a regular table:SELECT name, email FROM active_customers ORDER BY signup_date DESC LIMIT 10;
name | email -----------+----------------------- Ada King | ada@example.com Sam Lee | sam@example.com
Why use a view
Simplify repeated queries. If several parts of an application (or several analysts) all run the same complex join with several conditions, wrapping it in a view means everyone writes
SELECT * FROM view_nameinstead of repeating the full query.Restrict what a user or role can see. A view can expose only certain columns or rows of an underlying table — for example, hiding a
salarycolumn or filtering out soft-deleted rows — and you grant access to the view rather than the base table. This is a common, lightweight way to enforce a security boundary at the database layer.Give a stable name to a query shape. Application code can depend on a view's column names staying the same even if the underlying tables are later restructured, as long as the view definition is updated to match.
Replacing and dropping a view
CREATE OR REPLACE VIEW to redefine an existing view without dropping it first — useful because dropping a view would also revoke any permissions granted on it and break anything that depends on it existing.CREATE OR REPLACE VIEW active_customers AS SELECT id, name, email, signup_date, last_login FROM customers WHERE status = 'active';
DROP VIEW:DROP VIEW active_customers;
CREATE OR REPLACE VIEW can add new columns to the end of the column list, but it cannot remove or reorder existing columns, or change a column's type. To do that, you must DROP VIEW and CREATE VIEW again from scratch.A view always sees current data
SELECT against a view re-executes the underlying query against the current state of the base tables, so a view can never show stale data.