Generate and execute dynamic DROP TABLE statements to remove every table in an Amazon Redshift schema.
Create SQL that iterates through pg_table_def
, builds one DROP TABLE IF EXISTS
statement per table, and executes those statements in a single transaction.
BEGIN;
-- build drop statements
SELECT 'DROP TABLE IF EXISTS "' || schemaname || '"."' || tablename || '" CASCADE;' AS stmt
INTO TEMP TABLE drop_cmds
FROM pg_table_def
WHERE schemaname = 'public'
GROUP BY schemaname, tablename;
-- run every drop
DO $$ DECLARE r RECORD; BEGIN
FOR r IN SELECT stmt FROM drop_cmds LOOP
EXECUTE r.stmt;
END LOOP;
END $$;
COMMIT;
IF EXISTS
prevents errors if a table was removed mid-script. CASCADE
removes dependent objects like views or foreign keys, ensuring a clean wipe.
Yes – add filters in the WHERE
clause (e.g., tablename LIKE 'tmp_%'
) or exclude critical tables with AND tablename NOT IN ('customers','orders')
.
The user running the script must own the tables or have superuser privileges. Without ownership, each DROP
will fail with an insufficient privilege
error.
Wrapping the script in BEGIN…COMMIT
lets you roll back if something goes wrong, preserving data safety during development.
Export the schema or take a snapshot before dropping to avoid accidental, irreversible data loss.
The script targets tables only, but CASCADE will automatically remove dependent views.
No. After COMMIT the data is gone. Restore from snapshots or backups.
No single command exists. You must loop through each table or recreate the database.