Batch drop foreign keys in postgreSQL

Andy Chiang
1 min readJul 22, 2020

I have lots tables need to remove foreign keys constraints, but I dont want to open table and delete it one by one, so I GOOGLE and found this.

-- list all table_constraintsselect * from information_schema.table_constraints where table_schema = 'public' and constraint_name like '%_fkey' order by "table_name";

Batch drop script

DO $$
DECLARE r RECORD;
BEGIN
for r in (select constraint_name, table_name from information_schema.table_constraints where table_schema = 'public' and constraint_name like '%_fkey' order by "table_name") LOOP
raise info '%','dropping '||r.table_name||' - '||r.constraint_name;
execute CONCAT('ALTER TABLE '||r.table_name||' DROP CONSTRAINT '||r.constraint_name);
END LOOP;
END;
$$;DO

It save my life.

REF:

Photo by Vincentiu Solomon on Unsplash

--

--

Andy Chiang

不多話,愛兩個寶貝,寫Python,愛騎車,聽音樂