In a PostgreSQL 9.3 database, if I define tables a
and b
as follows:
CREATE TABLE a(i integer);
ALTER TABLE a ADD CONSTRAINT pkey_a
I agree with others that the right way to do it is in the right order - but there are just times when that is not a feasible option and something easier is needed to get the job done within the time budget.
In case this helps anyone, I made a procedure that will automate adding the deferred option to all FKs so that the
SET CONSTRAINTS ALL DEFERRED;
command will work. Use it only as necessary of course.
DO
$$
DECLARE
temp_rec RECORD;
sql_exe TEXT;
BEGIN
sql_exe := $sql$
ALTER TABLE %1$s ALTER CONSTRAINT %2$s DEFERRABLE;
$sql$
;
FOR temp_rec IN
(select constraint_name, table_name from information_schema.table_constraints where constraint_type = 'FOREIGN KEY')
LOOP
EXECUTE format(sql_exe, temp_rec.table_name, temp_rec.constraint_name);
END LOOP;
END;
$$
LANGUAGE plpgsql
;