Is there a postgres command to list/drop all materialized views?

有些话、适合烂在心里 提交于 2019-11-30 17:12:20

Show all:

SELECT oid::regclass::text
FROM   pg_class
WHERE  relkind = 'm';

Names are automatically double-quoted and schema-qualified where needed according to your current search_path in the cast from regclass to text.

In the system catalog pg_class materialized views are tagged with relkind = 'm'.
The manual:

m = materialized view

To drop all, you can generate the needed SQL script with this query:

SELECT 'DROP MATERIALIZED VIEW ' || string_agg(oid::regclass::text, ', ') 
FROM   pg_class
WHERE  relkind = 'm';

Returns:

DROP MATERIALIZED VIEW mv1, some_schema_not_in_search_path.mv2, ...

One DROP MATERIALIZED VIEW statement can take care of multiple materialized views. You may need to add CASCADE at the end if you have nested views.

Inspect the resulting DDL script to be sure before executing it. Are you sure you want to drop all MVs from all schemas in the db? And do you have the required privileges to do so? (Currently there are no materialized views in a fresh standard installation.)

This would be easier if you want to get a full list with the DROP statement in front of each view:

SELECT 'DROP MATERIALIZED VIEW ' || relname || ';' 
FROM   pg_class
WHERE  relkind = 'm';

This an answer is based on the answer from Erwin Brandstetter. The version below adds a specific schema name to only retrieve the materialized views from a defined schema. The Cascasde also drops dependencies on the materialized views from that schema. Be careful with that.

SELECT 'DROP MATERIALIZED VIEW <<schema_name>>.' || c.relname::text || ' CASCADE;' AS drop_statements
FROM pg_class c
INNER JOIN pg_namespace n ON n.oid = c.relnamespace
AND c.relkind = 'm'
AND n.nspname = '<<schema_name>>'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!