When working with partitions, there is often a need to delete all partitions at once.
However
DROP TABLE tablename*
Does not work. (The wildcard is not respected).
Is there an elegant (read: easy to remember) way to drop multiple tables in one command with a wildcard?
SQL92 and PostgreSQL do not allow (per standard) to delete data in multiple tables. In MySQL, this query deletes all records in history, term_node and term_date at once. PostgreSQL and the SQL Standard have other ways to delete from multiple tables: On DELETE CASCADE foreign keys can be used.
You can remove multiple tables from a database in one statement in PostgreSQL by specifying the comma-separated name of the tables after the statement DROP TABLE. The syntax is as follow: DROP TABLE [IF EXISTS] table_name1, table_name2, ... ... ... table_nameN [CASCADE | RESTRICT];
Wildcards in PostgreSQL is used to find matching rows values from tables; it is also used to find matching patterns rows from tables, Wildcards is also used to find matching rows, column and tables names; the output of the wildcard operator will return matching name, which was table name, column name or rows, In ...
We can drop multiple tables together using a single DROP Table statement as well. Let's create three tables and later we will drop it.
Use a comma separated list:
DROP TABLE foo, bar, baz;
If you realy need a footgun, this one will do it's job:
CREATE OR REPLACE FUNCTION footgun(IN _schema TEXT, IN _parttionbase TEXT) RETURNS void LANGUAGE plpgsql AS $$ DECLARE row record; BEGIN FOR row IN SELECT table_schema, table_name FROM information_schema.tables WHERE table_type = 'BASE TABLE' AND table_schema = _schema AND table_name ILIKE (_parttionbase || '%') LOOP EXECUTE 'DROP TABLE ' || quote_ident(row.table_schema) || '.' || quote_ident(row.table_name) || ' CASCADE '; RAISE INFO 'Dropped table: %', quote_ident(row.table_schema) || '.' || quote_ident(row.table_name); END LOOP; END; $$; SELECT footgun('public', 'tablename');
Here's another hackish answer to this problem. It works in ubuntu
and maybe some other os too. do a \dt
in postgres command prompt(the command prompt was running inside genome-terminal
in my case). Then you'll see a lot of tables in the terminal. Now use ctrl+click-drag
functionality of the genome-terminal
to copy all tables' names. Open python, do some string processing(replace ' ' by '' and then '\n' by ',') and you get comma separated list of all tables. Now in psql shell do a drop table CTRL+SHIFT+V
and you're done. I know it's too specific I just wanted to share. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With