If you have a UNIQUE
or PRIMARY KEY
constraint on table2.t1col
, like you most probably should, there is a more elegant solution for Postgres 9.5 (currently beta, to be released real soon now). Use the new UPSERT implementation INSERT ... ON CONFLICT DO NOTING
. Quoting the manual:
The optional ON CONFLICT
clause specifies an alternative action to
raising a unique violation or exclusion constraint violation error.
For each individual row proposed for insertion, either the insertion
proceeds, or, if an arbiter constraint or index specified by
conflict_target
is violated, the alternative conflict_action is taken.
ON CONFLICT DO NOTHING
simply avoids inserting a row as its alternative action.
Bold emphasis mine.
So you can simply:
INSERT INTO table2(t1col)
SELECT id FROM table1
ON CONFLICT DO NOTHING;
If table1.id
is not defined unique, make it unique:
INSERT INTO table2(t1col)
SELECT DISTINCT id FROM table1
ON CONFLICT DO NOTHING;
For Postgres 9.4 you can find a overview of techniques here: