Postgres Run Query on Multiple Tables

By Tyler on

If a query needs to be run on multiple tables with similar schemas, use this anonymous code block to reduce repetition.

DO $$
DECLARE
  current_table text;
BEGIN
    FOREACH current_table IN ARRAY ARRAY['table1', 'table2']
    LOOP
        EXECUTE format('DELETE FROM %I WHERE foo = %L', current_table, 'bar');
    END LOOP;
END $$;