Insert if not exists else update it in Netezza

2019-06-01 07:33发布

问题:

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

回答1:

Assuming you are providing an ID and want to UPSERT a single row in new_table with values from old_table. I am using a data-modifying CTE, which requires Postgres 9.1 or later:

WITH input AS (SELECT 123 AS id)
, upd AS (
   UPDATE new_table n
   SET    name = o.name
        , location = o.location
   FROM   old_table o, input i
   WHERE  n.id = o.id
   AND    n.id = i.id
   RETURNING id
   )
INSERT INTO new_table (id, name, location)
SELECT o.id, o.name, o.location
FROM   old_table o, input i 
WHERE  NOT EXISTS (SELECT 1 FROM upd)
AND    o.id = i.id;

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:

WITH upd AS (
   UPDATE new_table n
   SET    name = o.name
        , location = o.location
   FROM   old_table o
   WHERE  n.id = o.id
   RETURNING id
   )
INSERT INTO new_table (id, name, location)
SELECT o.id, o.name, o.location
FROM   old_table o
LEFT   JOIN upd u USING (id)
WHERE  u.id IS NULL;