I am having issue using if not exists statement in Netezza. I am trying to check if record is not there first then insert else update the record. I could not find a better way to do this in Netezza. Here is what I have but does not work:
IF NOT EXISTS(SELECT ID FROM OLD_TABLE WHERE ID NOT IN (SELECT ID FROM NEW TABLE ) )
INSERT INTO NEW_TABLE (NAME, LOCATION)
ELSE
UPDATE NEW_TABLE
SET NAME = X.NAME
FROM (SELECT NAME, LOCATION FROM OLD_TABLE)AS X
WHERE X.NAME = NEW_TABLE.NAME
Assuming you are providing an ID and want to UPSERT a single row in
new_table
with values fromold_table
. I am using a data-modifying CTE, which requires Postgres 9.1 or later:Here is a closely related answer with more explanation:
Problems with a PostgreSQL upsert query
There is a tiny chance for a race condition. If you are planning to use this under heavy concurrent load, consider this related question and the links for more:
Upsert with a transaction
Whole table
To upsert the whole table: