Sub topic 10
Altering, renaming, and dropping materialized views
This chapter covers how to change a materialized view after you have created it, and how to remove one safely. It assumes you have read the earlier chapters on creating, indexing, and refreshing materialized views. It reuses the orders table and the sales_daily view from those chapters. You should be comfortable with ALTER TABLE and DROP TABLE on ordinary tables.
What ALTER can and cannot change
ALTER MATERIALIZED VIEW changes the properties of a view that already exists: its name, schema, owner, column names, and storage settings. It cannot change the query that defines the view. There is no CREATE OR REPLACE MATERIALIZED VIEW, and no ALTER action that edits the stored SELECT. To change the query you must drop and recreate the view, or build a replacement and swap it in. The swap pattern appears later in this chapter.
| Action | Example | Notes |
|---|---|---|
| Rename the view | `RENAME TO new_name` | Dependent objects follow the view automatically. |
| Rename a column | `RENAME COLUMN a TO b` | Changes the output column name only. |
| Move to another schema | `SET SCHEMA reporting` | Indexes move with the view. |
| Change the owner | `OWNER TO analyst` | Needs privileges on the new owner role. |
| Storage parameters | `SET (fillfactor = 90)` | Applies to the stored rows. |
| Column statistics | `ALTER COLUMN revenue SET STATISTICS 500` | Affects planner estimates after the next `ANALYZE`. |
| Physical order | `CLUSTER ON index_name` | Records the index that `CLUSTER` should use. |
Only the owner of a materialized view, or a superuser, can alter or drop it.
Renaming a view, its columns, and its indexes
Renaming a view is a metadata change. PostgreSQL stores references between objects by internal object ID, not by name, so views that select from a renamed materialized view keep working.
ALTER MATERIALIZED VIEW sales_daily RENAME TO daily_sales;Renaming a column works the same way:
ALTER MATERIALIZED VIEW daily_sales RENAME COLUMN revenue TO total_revenue;Two things do not follow a rename.
- Index names. An index on the view keeps its old name, so
sales_daily_day_idxremains after the view becomesdaily_sales. Rename it yourself if you want the names to match:ALTER INDEX sales_daily_day_idx RENAME TO daily_sales_day_idx; - Names inside strings. A
pg_cronjob, an application query, or a shell script that contains the textREFRESH MATERIALIZED VIEW CONCURRENTLY sales_dailyis only a string to the database. After a rename it fails withrelation "sales_daily" does not exist. You have to update each of them by hand.
Renaming a column in the materialized view does not touch the base table. The reverse also applies: renaming a column on orders leaves the view working, but the view's output column keeps the name it had.
Moving and changing ownership
Use SET SCHEMA to move a view, for example into a schema reserved for reporting objects:
CREATE SCHEMA IF NOT EXISTS reporting;
ALTER MATERIALIZED VIEW daily_sales SET SCHEMA reporting;
SELECT * FROM reporting.daily_sales ORDER BY day DESC LIMIT 3;Unqualified queries now fail unless reporting is on the search_path. As with renames, anything that refers to the old name as text must change.
Ownership matters because a refresh runs with the privileges of whoever issues it. Only the owner can refresh the view, and a scheduled job must run as a role that has that right. Transfer ownership with:
ALTER MATERIALIZED VIEW reporting.daily_sales OWNER TO analyst;Moving a view, or changing its owner, does not change the privileges already granted on it.
Storage and statistics options
A materialized view is stored like a table, so several table-level tuning options apply to it. These are rarely needed, but each solves a specific problem.
-- Leave free space in each page. Useful if you expect many updates.
ALTER MATERIALIZED VIEW sales_daily SET (fillfactor = 90);
-- Collect a larger statistics sample for a column used in many filters.
ALTER MATERIALIZED VIEW sales_daily ALTER COLUMN day SET STATISTICS 500;
ANALYZE sales_daily;A normal refresh rewrites the whole stored relation, so fillfactor has limited effect. It matters more for the CONCURRENTLY variant, which applies row-level changes to the existing relation.
You can also record a clustering index and physically reorder the stored rows once:
ALTER MATERIALIZED VIEW sales_daily CLUSTER ON sales_daily_day_idx;
CLUSTER sales_daily;A refresh without CONCURRENTLY replaces the contents with the query's own output order. Any physical order from CLUSTER is lost after that refresh, though the CLUSTER ON setting remains.
Changing the defining query: replace by swap
Suppose you want to add an average order value to sales_daily. ALTER cannot do this. The simplest approach is DROP followed by CREATE, but between those two statements the view does not exist, and queries against it fail. For a view that applications read continuously, build the replacement under a temporary name and swap the names in one short transaction.
First, do the slow work outside any transaction. Building the new view runs the full aggregate query, but nobody reads the new object yet.
CREATE MATERIALIZED VIEW sales_daily_new AS
SELECT order_date AS day,
count(*) AS orders,
sum(total) AS revenue,
avg(total) AS avg_order
FROM orders
GROUP BY order_date;
CREATE UNIQUE INDEX sales_daily_new_day_idx ON sales_daily_new (day);The index gets a different name from the existing sales_daily_day_idx. Index names must be unique within a schema, and the old index still exists at this point.
Then swap inside a transaction that does only fast metadata operations:
BEGIN;
ALTER MATERIALIZED VIEW sales_daily RENAME TO sales_daily_old;
ALTER MATERIALIZED VIEW sales_daily_new RENAME TO sales_daily;
DROP MATERIALIZED VIEW sales_daily_old;
ALTER INDEX sales_daily_new_day_idx RENAME TO sales_daily_day_idx;
COMMIT;Dropping the old view removes its index, which frees the name sales_daily_day_idx for the final rename.
Both RENAME and DROP take an ACCESS EXCLUSIVE lock, and PostgreSQL holds locks until the transaction ends. Readers of sales_daily wait from the first rename until COMMIT. Because every step in the transaction is a catalog change, the wait is typically milliseconds. A long-running query that is still reading the old view delays the lock, and later queries queue behind it. Set a lock_timeout in the session if you would rather fail than wait.
Three side effects of the swap catch people out:
- Privileges are not copied. The new view starts with default privileges. Re-grant what readers need, for example
GRANT SELECT ON sales_daily TO reporting;, ideally inside the same transaction. - Dependent views block the drop. A view built on
sales_dailydepends on the old object, which keeps its identity through the rename.DROP MATERIALIZED VIEW sales_daily_oldthen fails unless you useCASCADE, andCASCADEwould remove the dependent view. Recreate those dependents against the new view first. - Indexes are not copied. Create every index you need on the new view before the swap.
Dropping a materialized view
DROP MATERIALIZED VIEW sales_daily;
DROP MATERIALIZED VIEW IF EXISTS sales_daily, customer_totals;IF EXISTS turns a missing view into a notice instead of an error, which helps in repeatable scripts. Dropping a view also drops its indexes and discards its stored rows. It does not touch the base tables.
DROP MATERIALIZED VIEW only works on materialized views. If the name belongs to a plain view or table, PostgreSQL returns an error that names the right command, such as DROP VIEW.
RESTRICT and CASCADE
The default is RESTRICT. If any other object depends on the view, the drop fails and lists the dependents:
CREATE VIEW top_days AS
SELECT day, revenue FROM sales_daily ORDER BY revenue DESC LIMIT 10;
DROP MATERIALIZED VIEW sales_daily;
-- ERROR: cannot drop materialized view sales_daily because other objects depend on it
-- DETAIL: view top_days depends on materialized view sales_daily
-- HINT: Use DROP ... CASCADE to drop the dependent objects too.DROP ... CASCADE removes the view and everything that depends on it, including top_days here. Read the DETAIL lines from a failed RESTRICT drop before you choose CASCADE. PostgreSQL lists what CASCADE would remove, and in a real database that list can include views you did not know existed.
How base-table changes interact with the view
A materialized view depends on the tables and columns its query uses. Changes to those objects behave like this:
| Change on `orders` | Result |
|---|---|
| `ALTER TABLE orders RENAME TO sales_orders` | Works. The view keeps its stored definition and refreshes against the renamed table. |
| `ALTER TABLE orders RENAME COLUMN total TO amount` | Works. The stored query follows the column. |
| `ALTER TABLE orders ADD COLUMN note text` | Works. The view does not gain the new column. |
| `ALTER TABLE orders ALTER COLUMN total TYPE bigint` | Fails with `cannot alter type of a column used by a view or rule`. |
| `ALTER TABLE orders DROP COLUMN total` | Fails unless you add `CASCADE`, which drops the view as well. |
| `DROP TABLE orders` | Fails unless you add `CASCADE`, which drops the view as well. |
The failing cases are a common migration problem. A schema migration that changes a column type has to drop the dependent materialized views first and recreate them afterwards, usually in the same migration transaction.
A pre-change checklist
Before you rename, move, or drop a materialized view, check these places:
- Scheduled refreshes. List
pg_cronjobs withSELECT jobid, jobname, command FROM cron.job;and fix any command that names the view. For a dropped view, remove the job withSELECT cron.unschedule('refresh-sales-daily');. - Dependent views and functions. A
RESTRICTdrop reports views. SQL functions that name the view as text, and PL/pgSQL bodies, are not tracked as dependencies and fail only when they run. - Privileges. Record the current grants, for example with
\dp sales_dailyinpsql, so that you can restore them on a replacement. - Current state. Run
SELECT schemaname, matviewname, matviewowner, ispopulated FROM pg_matviews;to confirm the owner, the schema, and whether the view holds data.
Exercise
You need to add a column to the query behind sales_daily, which a dashboard reads all day. Why is ALTER MATERIALIZED VIEW not the right tool, and which steps avoid a period where the view does not exist?
Show answer
ALTER MATERIALIZED VIEW cannot edit the defining query. Build sales_daily_new with the new query and its unique index (with a different index name) outside a transaction. Then, in one short transaction, rename sales_daily to sales_daily_old, rename sales_daily_new to sales_daily, drop the old view, rename the new index, and re-grant privileges. Readers are blocked only for the brief rename and drop locks.
Exercise
You rename sales_daily to daily_sales. A pg_cron job still runs REFRESH MATERIALIZED VIEW CONCURRENTLY sales_daily. What happens, and what else keeps its old name?
Show answer
The job fails with relation "sales_daily" does not exist, because the cron command is plain text that PostgreSQL does not update. Fix it by unscheduling the job and scheduling it again with the new name. The view's index, such as sales_daily_day_idx, also keeps its old name until you rename it with ALTER INDEX ... RENAME TO.
Exercise
DROP MATERIALIZED VIEW sales_daily; fails because a view top_days depends on it. What are your options, and which is safer to try first?
Show answer
Read the DETAIL output to see what depends on the view. You can drop or rewrite top_days first, then drop sales_daily, or use DROP MATERIALIZED VIEW sales_daily CASCADE; to remove both. The first option is safer because CASCADE removes every dependent object, including ones you may not have known about.