Sub topic 7
Creating an unpopulated view with WITH NO DATA
This chapter assumes you can already run CREATE MATERIALIZED VIEW and REFRESH MATERIALIZED VIEW, and that you know what a unique index is. It covers the WITH NO DATA clause. This clause creates a materialized view's definition without running its query, which is useful for migrations, dumps and restores, and staged deployments.
What WITH NO DATA does
By default, CREATE MATERIALIZED VIEW behaves as if you had written WITH DATA. PostgreSQL runs the query, stores the rows, and returns when the work is done. For a large aggregate this can take minutes.
WITH NO DATA skips that step. PostgreSQL parses and plans the query, records the view's definition and column types in the catalog, and stores nothing. The view exists but is marked as unpopulated, which means it cannot be scanned.
CREATE TABLE orders (
id bigserial PRIMARY KEY,
customer_id integer NOT NULL,
order_date date NOT NULL,
total numeric(10,2) NOT NULL
);
CREATE MATERIALIZED VIEW customer_totals AS
SELECT customer_id, sum(total) AS lifetime_value
FROM orders
GROUP BY customer_id
WITH NO DATA;The statement returns almost instantly, however large orders is. The query still has to be valid. A misspelled column or a missing table fails at creation time. Errors that depend on the data, such as division by zero in an expression, only appear at the first refresh.
Unpopulated is not the same as empty
An unpopulated view and a populated view with zero rows behave differently.
- A populated view whose query matched no rows returns an empty result set.
- An unpopulated view raises an error when you read it.
SELECT * FROM customer_totals;ERROR: materialized view "customer_totals" has not been populated
HINT: Use the REFRESH MATERIALIZED VIEW command.The error is deliberate. An empty result would look like "there are no customers," which could be wrong. The error makes it clear the view has never been filled.
Checking whether a view is populated
The pg_matviews catalog view has an ispopulated column. Use it to check state without triggering the error.
SELECT matviewname, ispopulated
FROM pg_matviews
WHERE matviewname = 'customer_totals'; matviewname | ispopulated
-----------------+-------------
customer_totals | fThe same flag is stored as relispopulated in pg_class. Prefer pg_matviews, because it is the documented, readable interface and includes the schema name. If you have views with the same name in several schemas, filter on schemaname as well.
Populating the view
A plain REFRESH MATERIALIZED VIEW runs the query and fills the view. It also flips ispopulated to true.
REFRESH MATERIALIZED VIEW customer_totals;
SELECT matviewname, ispopulated
FROM pg_matviews
WHERE matviewname = 'customer_totals';After this, ispopulated is t, and SELECT * FROM customer_totals returns rows.
The refresh takes an ACCESS EXCLUSIVE lock, so it blocks readers. For a view that has never been populated, that costs nothing. No one can read it anyway, so the first refresh is the one case where a blocking refresh is harmless.
Going back to unpopulated
REFRESH also accepts WITH NO DATA. It discards the stored rows and marks the view unpopulated again.
REFRESH MATERIALIZED VIEW customer_totals WITH NO DATA;This is useful when you want to free disk space for a view that is rarely used. It also resets the view to a known state before a maintenance task. Reads fail again until the next normal refresh.
The statement forms and their effects:
| Statement | Runs the query | Result state |
|---|---|---|
| `CREATE MATERIALIZED VIEW v AS ...` | Yes | Populated |
| `CREATE MATERIALIZED VIEW v AS ... WITH NO DATA` | No | Unpopulated |
| `REFRESH MATERIALIZED VIEW v` | Yes | Populated |
| `REFRESH MATERIALIZED VIEW v WITH NO DATA` | No | Unpopulated |
| `REFRESH MATERIALIZED VIEW CONCURRENTLY v` | Yes | Populated, only if already populated |
The state machine
The diagram shows every way a view moves between the two states.
CONCURRENTLY needs a populated view
REFRESH MATERIALIZED VIEW CONCURRENTLY works by building the new result in a temporary table and comparing it with the existing rows. If there are no existing rows to compare against, the approach does not apply. So PostgreSQL rejects the command on an unpopulated view.
CREATE UNIQUE INDEX customer_totals_customer_idx
ON customer_totals (customer_id);
REFRESH MATERIALIZED VIEW CONCURRENTLY customer_totals WITH NO DATA;ERROR: CONCURRENTLY and WITH NO DATA options cannot be used togetherIf you run CONCURRENTLY on a view that was created WITH NO DATA and never refreshed, you get a different error:
ERROR: CONCURRENTLY cannot be used when the materialized view is not populatedThe fix for the second case is a plain REFRESH first. After that, CONCURRENTLY is available, provided the view has a unique index that covers plain columns and all rows.
This matters for scheduled jobs. A job that always runs REFRESH ... CONCURRENTLY fails on a freshly created, unpopulated view until someone populates it by hand. The next section shows a defensive pattern.
Indexes on an unpopulated view
You can create indexes on an unpopulated view. Index creation on an empty relation is fast, and the indexes are filled when the view is populated.
CREATE MATERIALIZED VIEW customer_totals AS
SELECT customer_id, sum(total) AS lifetime_value
FROM orders
GROUP BY customer_id
WITH NO DATA;
CREATE UNIQUE INDEX customer_totals_customer_idx
ON customer_totals (customer_id);
REFRESH MATERIALIZED VIEW customer_totals;Creating the unique index before the first refresh has two benefits. The definition is complete in one migration, including what CONCURRENTLY will need later. And the index is built as part of the refresh, so you do not run a second pass over the data.
If you create the view with data and then add indexes, the rows are written first and each index is built afterward. Both orders produce the same final state. The WITH NO DATA order lets you split the cheap schema work from the expensive data work.
A refresh job that handles both states
You can write a single script that works on both new and established views. It chooses the refresh mode from ispopulated.
DO $$
BEGIN
IF (SELECT ispopulated
FROM pg_matviews
WHERE schemaname = 'public'
AND matviewname = 'customer_totals') THEN
REFRESH MATERIALIZED VIEW CONCURRENTLY customer_totals;
ELSE
REFRESH MATERIALIZED VIEW customer_totals;
END IF;
END
$$;You can pass this block to psql from cron or another scheduler, or wrap it in a function and call it from a pg_cron job. Because the IF reads the catalog at run time, the same job works before and after the first population.
When to use WITH NO DATA
Fast, predictable migrations
Schema migrations often run inside a transaction with a lock timeout. A materialized view that takes ten minutes to build is a poor fit. Create the view WITH NO DATA in the migration, which finishes in milliseconds. Populate it in a separate, monitored step, or let your first scheduled refresh do it.
The application must not query the view before it is populated, or it will hit the error shown earlier. Either order the deployment so that population finishes before the code that reads the view goes live, or have the application handle the error.
Dumps and restores
pg_dump records a materialized view's definition as CREATE MATERIALIZED VIEW ... WITH NO DATA. It then emits a REFRESH MATERIALIZED VIEW command in a later part of the dump, once the base tables are loaded. In a schema-only dump (pg_dump --schema-only), the refresh is left out, so a restored copy contains unpopulated views. If your test environment is built from a schema-only dump, expect ispopulated to be false until you refresh.
Staging environments and disk space
On a development or staging database, you may want the structure of every view without the cost of computing all of them. Creating with WITH NO DATA keeps the database small and builds fast. Refresh only the views you need.
Common mistakes
- Reading before refreshing. The error message points to the fix, but a deploy can still fail if nothing populates the view. Add population to the deployment checklist.
- Using
CONCURRENTLYon the first refresh. It fails on an unpopulated view. Use a plain refresh first, or theIFpattern above. - Confusing empty and unpopulated. A monitoring query that counts rows will itself raise the error on an unpopulated view. Check
ispopulatedfirst. - Forgetting that
REFRESH ... WITH NO DATAdiscards data. It is immediate, and the old rows are not kept. Do not use it as a "clear cache" step on a view that serves live traffic. - Assuming
WITH NO DATAskips validation. The query is still planned. Only data-dependent errors are postponed.
Putting it together
This script creates a view, indexes it, confirms it is unpopulated, populates it, and then schedules recurring refreshes with the check built in.
CREATE MATERIALIZED VIEW sales_daily AS
SELECT order_date AS day,
count(*) AS orders,
sum(total) AS revenue
FROM orders
GROUP BY order_date
WITH NO DATA;
CREATE UNIQUE INDEX sales_daily_day_idx ON sales_daily (day);
SELECT ispopulated FROM pg_matviews WHERE matviewname = 'sales_daily';
REFRESH MATERIALIZED VIEW sales_daily;
SELECT ispopulated FROM pg_matviews WHERE matviewname = 'sales_daily';
REFRESH MATERIALIZED VIEW CONCURRENTLY sales_daily;The first check returns f, the second returns t, and the final concurrent refresh succeeds because the view is now populated and has a unique index.
Summary
WITH NO DATAcreates the definition and skips the query, so creation is nearly instant.- An unpopulated view raises an error when read, which is different from returning zero rows.
pg_matviews.ispopulatedtells you the state without raising the error.- A plain
REFRESHpopulates the view, andREFRESH ... WITH NO DATAempties it again. CONCURRENTLYrequires a populated view, so the first refresh must be a plain one.pg_dumpuses this mechanism, so restored views may need a refresh.
Exercise
You created a materialized view with WITH NO DATA and a unique index. A scheduled job runs REFRESH MATERIALIZED VIEW CONCURRENTLY on it every 15 minutes and fails every time. What is the cause, and what is the smallest change that fixes it permanently?
Show answer
The view has never been populated, and CONCURRENTLY cannot be used on an unpopulated view (error: "CONCURRENTLY cannot be used when the materialized view is not populated"). Run one plain REFRESH MATERIALIZED VIEW to populate it, after which the scheduled concurrent refreshes succeed. To make the job robust, wrap it in a block that checks pg_matviews.ispopulated and uses a plain refresh when the view is not populated.
Exercise
A teammate says that SELECT count(*) FROM customer_totals returning an error proves the view is broken. What is the likely explanation, and how can you confirm it without querying the view?
Show answer
The view is probably unpopulated because it was created WITH NO DATA (or restored from a schema-only dump) and never refreshed. Reading an unpopulated view raises "has not been populated". Confirm with SELECT ispopulated FROM pgmatviews WHERE matviewname = 'customertotals'; a value of f means it needs REFRESH MATERIALIZED VIEW.
Exercise
Which of these statements leaves the view unpopulated: (a) CREATE MATERIALIZED VIEW v AS SELECT 1 AS x; (b) CREATE MATERIALIZED VIEW v AS SELECT 1 AS x WITH NO DATA; (c) REFRESH MATERIALIZED VIEW v WITH NO DATA on a populated view; (d) REFRESH MATERIALIZED VIEW CONCURRENTLY v on a populated view with a unique index?
Show answer
(b) and (c). Statement (a) defaults to WITH DATA, and (d) re-runs the query and keeps the view populated.