Browse topics

Views and materialized views

Version
19
Review
Draft

Summary#

A view runs its stored query when you read it. A materialized view saves the query result, so reads can be faster but stay unchanged until a refresh.

Syntax#

sql
CREATE VIEW view_name AS query;

CREATE MATERIALIZED VIEW cache_name AS query;

REFRESH MATERIALIZED VIEW [CONCURRENTLY] cache_name;

Example#

The output below is from PostgreSQL 19.0, produced with psql -X -q -A -P null=NULL -v ON_ERROR_STOP=1 -f example.sql in a scratch database. The script creates a schema inside a transaction and rolls it back. The database user needs permission to create schemas.

sql
BEGIN;

CREATE SCHEMA devlookup_views;
SET LOCAL search_path = devlookup_views;

CREATE TABLE payments (
    payment_id integer PRIMARY KEY,
    customer   text NOT NULL,
    amount     integer NOT NULL
);

INSERT INTO payments VALUES (1, 'oak', 30), (2, 'pine', 45), (3, 'oak', 20);

-- A view stores the query.
CREATE VIEW customer_totals AS
SELECT customer, sum(amount) AS total
FROM payments
GROUP BY customer;

-- A materialized view stores the rows.
CREATE MATERIALIZED VIEW customer_totals_cache AS
SELECT customer, total FROM customer_totals;

CREATE UNIQUE INDEX customer_totals_cache_key
    ON customer_totals_cache (customer);

INSERT INTO payments VALUES (4, 'pine', 5);

SELECT v.customer, v.total AS from_view, m.total AS from_cache
FROM customer_totals AS v
JOIN customer_totals_cache AS m USING (customer)
ORDER BY v.customer;

REFRESH MATERIALIZED VIEW CONCURRENTLY customer_totals_cache;

SELECT customer, total
FROM customer_totals_cache
ORDER BY customer;

ROLLBACK;

Expected output#

Text
customer|from_view|from_cache
oak|50|50
pine|50|45
(2 rows)
customer|total
oak|50
pine|50
(2 rows)

Common mistakes#

Refresh explicitly after changes to the base tables. REFRESH ... CONCURRENTLY keeps the materialized view readable during refresh. It needs an already populated materialized view with a unique index on plain columns covering all rows. PostgreSQL runs one refresh at a time per materialized view.

Version applicability#

Materialized views require PostgreSQL 9.3, and concurrent refresh requires 9.4. Ordinary views also work on earlier versions.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0