how about this solution? Does it have any caveats? WITH upsert AS (INSERT INTO GUCIO (ID, NAZWA) SELECT A.ID, A.NAZWA FROM ALA A ON CONFLICT (ID) DO UPDATE SET nazwa = excluded.nazwa RETURNING xmax,xmin, *) select xmax as xmax_value into txmaxu from upsert; delete from gucio where xmax = (select xmax_value from txmaxu where xmax_value <> 0 limit 1); -- Sent from: https://www.postgresql-archive.org/PostgreSQL-general-f1843780.html