Skip to content

Instantly share code, notes, and snippets.

@Harkishen-Singh
Last active August 7, 2023 13:47
Show Gist options
  • Save Harkishen-Singh/ae34f44e6767586832fba71fbcec2c5a to your computer and use it in GitHub Desktop.
Save Harkishen-Singh/ae34f44e6767586832fba71fbcec2c5a to your computer and use it in GitHub Desktop.
A PLPGSQL script to truncate all tables in a given list of schemas
-- Usage: SELECT truncate_all_tables_in_schemas(ARRAY['schema1', 'schema2', 'schema3']);
CREATE OR REPLACE FUNCTION truncate_all_tables_in_schemas(schema_names text[]) RETURNS void AS $$
DECLARE 
   schema_name text;
   table_name text; 
BEGIN 
   FOREACH schema_name IN ARRAY schema_names
   LOOP
      FOR table_name IN (SELECT tablename FROM pg_tables WHERE schemaname = schema_name) 
      LOOP 
         EXECUTE 'TRUNCATE TABLE ' || schema_name || '.' || table_name; 
      END LOOP; 
   END LOOP;
END $$ LANGUAGE plpgsql;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment