drop multiple tables using do block in PostgreSQL

Sometimes we want to drop all the tables in a database with a particular naming convention, below is the simple SQL script which drop all the tables in a database with naming convention like “test_temp_****”.
DO
$$
DECLARE
query text;
rec record;
BEGIN
query='select schemaname, tablename from pg_tables where tablename like ''test_temp_%''';
FOR rec IN EXECUTE query
LOOP
RAISE NOTICE 'drop table %.%',rec.schemaname,rec.tablename;
EXECUTE 'drop table ' || rec.schemaname||'.'||rec.tablename;
END LOOP;
END;
$$;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s