Sub topic 1
Views, materialized views, and tables: what is stored and what is not
Prerequisites
This chapter assumes you know basic SQL, including SELECT, GROUP BY, and aggregate functions such as count and sum. You should understand tables and plain views, and have access to a PostgreSQL server through psql or another SQL client.
How each object stores data
A table stores its rows on disk. Queries read those rows directly.
A plain view stores no rows. It stores only a saved SELECT statement. Each time you query the view, PostgreSQL runs that SELECT against the base tables. The result is always current, but heavy aggregates can be slow.
A materialized view stores the result of its query as rows on disk. It can also have indexes. Queries read the stored rows and never touch the base tables. The stored rows do not change when the base table changes, so you must refresh the view to update them.
CREATE TABLE orders (
id bigserial PRIMARY KEY,
customer_id integer NOT NULL,
order_date date NOT NULL,
total numeric(10,2) NOT NULL
);Creating a materialized view
Use CREATE MATERIALIZED VIEW with an AS clause that holds the query. PostgreSQL runs the query once, at creation time, and saves the result.
CREATE MATERIALIZED VIEW sales_daily AS
SELECT order_date AS day,
count(*) AS orders,
sum(total) AS revenue
FROM orders
GROUP BY order_date;
SELECT * FROM sales_daily ORDER BY day DESC LIMIT 7;You query a materialized view with ordinary SELECT statements, just as you would a table.
Refreshing data with REFRESH MATERIALIZED VIEW
REFRESH MATERIALIZED VIEW reruns the stored query and replaces the saved rows. The following example shows the view before and after a refresh.
INSERT INTO orders (customer_id, order_date, total)
VALUES (1, CURRENT_DATE, 25.00);
-- Returns the old result, with no row for today if no earlier orders exist:
SELECT * FROM sales_daily WHERE day = CURRENT_DATE;
REFRESH MATERIALIZED VIEW sales_daily;
-- Now includes the new order:
SELECT * FROM sales_daily WHERE day = CURRENT_DATE;Exercise
After you insert a new order, why does a plain view show it immediately but a materialized view does not?
Show answer
A plain view runs its saved SELECT on every query, so it reads the current base table rows. A materialized view reads its stored copy, which changes only when you run REFRESH MATERIALIZED VIEW.