Views

Topic 1 of 4 in Beyond the basics10 min readBeginnerFree course

Overview

Some queries get written again and again: order totals with customer names, revenue by product, active customers. Copying the same joins into every report is tedious and risky — two analysts write it slightly differently and their numbers disagree. A view is a saved query with a name. Once created, you can query it like a table, and everyone uses the same definition.

Views: saved queries that behave like tables. The tables orders, order_items and customers feed into VIEW order_summary — a stored SELECT with no data of its own — which is used by reports and analysts. CREATE VIEW order_summary AS SELECT o.id, c.first_name, o.status, sum(oi.quantity * oi.unit_price) AS items_total FROM orders o JOIN customers c ON c.id = o.customer_id JOIN order_items oi ON oi.order_id = o.id GROUP BY o.id, c.first_name; then SELECT * FROM order_summary WHERE items_total > 100. A view runs its query every time you select from it, so it always shows current data. A MATERIALIZED VIEW stores the result instead: fast to read, but stale until REFRESH MATERIALIZED VIEW.

Creating and using a view

SQL
CREATE VIEW order_summary AS
SELECT o.id,
       c.first_name,
       o.ordered_at::date AS day,
       o.status,
       sum(oi.quantity * oi.unit_price) AS items_total,
       o.shipping_fee
FROM orders AS o
JOIN customers AS c    ON c.id = o.customer_id
JOIN order_items AS oi ON oi.order_id = o.id
GROUP BY o.id, c.first_name;
Text
CREATE VIEW

The view stores no data — just the query. Now the joins and grouping are hidden behind a single name, and you can filter, sort and aggregate the view like any table:

SQL
SELECT id, first_name, day, items_total
FROM order_summary
WHERE items_total > 100
ORDER BY items_total DESC;
Text
 id | first_name |    day     | items_total 
----+------------+------------+-------------
  2 | Ben        | 2026-01-12 |      113.00
 21 | Ben        | 2026-10-27 |      109.00
(2 rows)
SQL
SELECT status, count(*) AS orders, sum(items_total + shipping_fee) AS billed
FROM order_summary
GROUP BY status
ORDER BY billed DESC;
Text
  status   | orders | billed 
-----------+--------+--------
 delivered |     16 | 914.62
 paid      |      2 | 162.49
 shipped   |      2 | 123.64
 cancelled |      2 |  82.39
 pending   |      2 |  70.25
(5 rows)

PostgreSQL merges your query with the view’s definition and optimises them together, so using a view is normally just as fast as writing the full query yourself.

Always up to date

Because a view runs its query each time, it reflects every change to the underlying tables immediately:

SQL
UPDATE orders SET status = 'shipped' WHERE id = 22;

SELECT id, first_name, status FROM order_summary WHERE id = 22;
Text
UPDATE 1
 id | first_name | status  
----+------------+---------
 22 | Farhan     | shipped
(1 row)

Why use views

  • Simplicity. Analysts query order_summary without having to know how orders, items and customers connect.
  • One definition. “Revenue” is calculated in one place. Fix the definition once, and every report that uses it is fixed.
  • Security and privacy. A view can expose some columns and rows and not others — say, customers without their emails and phone numbers — and users can be given access to the view but not the table (see Users and permissions).
  • Stable interfaces. If you restructure the tables, you can keep an old view working so existing reports don’t break.
SQL
CREATE VIEW customer_directory AS
SELECT id, first_name, city, country
FROM customers;

SELECT * FROM customer_directory WHERE country = 'India' ORDER BY id;
Text
CREATE VIEW
 id | first_name |  city  | country 
----+------------+--------+---------
  1 | Asha       | Pune   | India
  6 | Farhan     | Pune   | India
  9 | Isha       | Mumbai | India
(3 rows)

Changing and dropping views

CREATE OR REPLACE VIEW redefines a view. It can add new columns at the end, but can’t remove or rename existing ones — for that, drop and recreate it:

SQL
CREATE OR REPLACE VIEW customer_directory AS
SELECT id, first_name, city, country, signup_date
FROM customers;

DROP VIEW customer_directory;
Text
CREATE VIEW
DROP VIEW

PostgreSQL tracks dependencies: you can’t drop a table or column that a view uses without dropping the view too (DROP … CASCADE does both — read its message carefully).

Updatable views

A simple view — one table, no GROUP BY, DISTINCT, joins or aggregates — can be updated through: INSERT, UPDATE and DELETE on the view change the underlying table.

SQL
CREATE VIEW out_of_stock AS
SELECT id, name, stock FROM products WHERE stock = 0;

UPDATE out_of_stock SET stock = 12 WHERE name = 'Glass Teapot';

SELECT name, stock FROM products WHERE name = 'Glass Teapot';
Text
CREATE VIEW
UPDATE 1
     name     | stock 
--------------+-------
 Glass Teapot |    12
(1 row)

The teapot is back in stock — and has therefore dropped out of the out_of_stock view. order_summary, with its joins and GROUP BY, is read-only: there’s no single row of a single table that a change to it would correspond to.

Materialized views

A normal view recalculates every time. For a heavy report over millions of rows, read often and needed only once an hour or once a day, that’s wasteful. A materialized view runs the query once and stores the result like a table:

SQL
CREATE MATERIALIZED VIEW monthly_revenue AS
SELECT date_trunc('month', o.ordered_at)::date AS month,
       sum(oi.quantity * oi.unit_price) AS revenue
FROM orders AS o
JOIN order_items AS oi ON oi.order_id = o.id
WHERE o.status <> 'cancelled'
GROUP BY 1;

SELECT * FROM monthly_revenue WHERE month >= '2026-10-01' ORDER BY month;
Text
SELECT 11
   month    | revenue 
------------+---------
 2026-10-01 |  147.50
 2026-11-01 |  102.75
(2 rows)

Reading it is as fast as reading a small table, and you can even index it. The catch: it’s a snapshot. Add an order, and the materialized view doesn’t notice:

SQL
INSERT INTO orders (customer_id, ordered_at, status) VALUES (9, '2026-11-30 10:00', 'paid');
INSERT INTO order_items (order_id, product_id, quantity, unit_price) VALUES (25, 9, 1, 89.00);

SELECT * FROM monthly_revenue WHERE month = '2026-11-01';
Text
INSERT 0 1
INSERT 0 1
   month    | revenue 
------------+---------
 2026-11-01 |  102.75
(1 row)

Until you refresh it:

SQL
REFRESH MATERIALIZED VIEW monthly_revenue;

SELECT * FROM monthly_revenue WHERE month = '2026-11-01';
Text
REFRESH MATERIALIZED VIEW
   month    | revenue 
------------+---------
 2026-11-01 |  191.75
(1 row)

Refreshes are usually scheduled (every night, every hour) with a job scheduler or the pg_cron extension. REFRESH MATERIALIZED VIEW CONCURRENTLY lets people keep reading the old data during the refresh, provided the view has a unique index.

View Materialized view
Stores data no yes
Always current yes only after a refresh
Speed as fast as the underlying query as fast as reading a table
Good for simplifying queries, security, shared definitions expensive reports, dashboards

Tip: name views so their nature is obvious — some teams prefix them (v_order_summary, mv_monthly_revenue) — and keep their definitions in your migrations like any other part of the schema.

Exercise

A product sales view

Create a view named product_sales with one row per product — including products that have never sold — and the columns product (the product name), category (the category name, or 'Uncategorised' if it has none), units (total quantity sold, 0 if none) and revenue (total quantity × unit price, 0 if none). Use LEFT JOINs from products. Then query the view for the three products with the highest revenue, highest first.

SQL
CREATE VIEW product_sales AS
SELECT p.name AS product
FROM products AS p;

SELECT * FROM product_sales;

Summary

  • A view is a named, stored SELECT; querying it runs the query, so it always reflects the current data.
  • Views simplify complex joins into a single name, give reports one agreed definition, and can expose only some columns or rows.
  • CREATE OR REPLACE VIEW changes a view's definition (adding columns at the end); DROP VIEW removes it.
  • Simple views on one table can be updated through; complex views (joins, GROUP BY) are read-only.
  • A MATERIALIZED VIEW stores its result: fast to read, but stale until REFRESH MATERIALIZED VIEW.