How to reduce foreign key performance impact in PostgreSQL Foreign keys add significant overhead...more than +600% in the example below (Docker PostgreSQL 11.4):

CREATE TABLE example_1 (a int PRIMARY KEY);
CREATE TABLE example_2 (a int NOT NULL REFERENCES example_1 (a));
CREATE TABLE example_3 (a int NOT NULL);

INSERT INTO example_1 SELECT generate_series(1, 1000);

-- with FK
INSERT INTO example_2 SELECT g FROM generate_series(1, 1000) g, generate_series(1, 10000);
Time: 91301.783 ms (01:31.302)

-- without FK
INSERT INTO example_3 SELECT g FROM generate_series(1, 1000) g, generate_series(1, 10000);
Time: 12395.756 ms (00:12.396)


Any ways to reduce this high FK overhead?
If you are a superuser, you can temporarily disable the system triggers that implement the foreign key checks:

BEGIN;
ALTER TABLE example_2 DISABLE TRIGGER ALL;
INSERT INTO example_2
   SELECT g FROM generate_series(1, 1000) g,
                 generate_series(1, 10000);
ALTER TABLE example_2 ENABLE TRIGGER ALL;
COMMIT;


Dire warning: Do this only if you are 100% certain that your data modifications will not produce inconsistencies. This is dangerous, which is also the reason why only superusers can do it.