How do I drop all tables in psql (PostgreSQL interactive terminal) that starts with a common word?

前端 未结 2 468
一个人的身影
一个人的身影 2021-01-14 21:23

How do I drop all tables whose name start with, say, doors_? Can I do some sort of regex using the drop table command?

I prefer not writing

2条回答
  •  心在旅途
    2021-01-14 21:39

    This script will generate the DDL commands to drop them all:

    SELECT 'DROP TABLE ' || t.oid::regclass || ';'
    FROM   pg_class t
    -- JOIN   pg_namespace n ON n.oid = t.relnamespace -- to select by schema
    WHERE  t.relkind = 'r'
    AND    t.relname ~~ E'doors\_%' -- enter search term for table here
    -- AND n.nspname ~~ '%myschema%' -- optionally select by schema(s), too
    ORDER  BY 1;
    

    The cast t.oid::regclass makes the syntax work for mixed case identifiers, reserved words or special characters in table names, too. It also prevents SQL injection and prepends the schema name where necessary. More about object identifier types in the manual.

    About the schema search path.

    You could automate the dropping, too, but it's unwise not to check what you actually delete before you do.

    You could append CASCADE to every statement to DROP depending objects (views and referencing foreign keys). But, again, that's unwise unless you know very well what you are doing. Foreign key constraints are no big loss, but this will also drop all dependent views entirely. Without CASCADE you get error messages informing you which objects prevent you from dropping the table. And you can then deal with it.

提交回复
热议问题