The NOT EXISTS
clause only prevents rows from temptable
conflicting with existing rows from realtable
; it will not prevent multiple rows from temptable
from conflicting with each other. This is because the SELECT
is calculated once based on the initial state of realtable
, not re-calculated after each row is inserted.
One solution would be to use a GROUP BY
or DISTINCT ON
in the SELECT
query, to omit duplicates, e.g.
INSERT INTO realtable
SELECT DISTINCT ON (added_date, product_name) *
FROM temptable WHERE NOT EXISTS (
SELECT 1 FROM realtable WHERE temptable.added_date = realtable.added_date
AND temptable.product_name = realtable.product_name
)
ORDER BY ???; -- this ORDER BY will determine which of a set of duplicates is kept by the DISTINCT ON