Search code examples
sqlpostgresqlinsert-update

updating for several columns with distinct conditions


I have INSERT statement where values are provided through SELECT from other table. ON CONFLICT I'm updating several columns. I'm just wondering if is possible to SET each column matching unique condition

Now I have solution which work, however it isn't ideal.

Basically something like this would match my desired result..

WITH table_a (
 --joining two tables
)

INSERT INTO table_b
SELECT * FROM table_a
ON CONFLICT
ON CONSTRAINT table_b_pkey DO UPDATE
SET column_a = EXCLUDED.column_a
WHERE table_b.column_a < EXCLUDED.column_a
OR 
SET column_b = EXCLUDED.column_b
WHERE table_b.column_b < EXCLUDED.column_b

Solution

  • Use CASE, e.g.:

    INSERT INTO table_b
    SELECT * FROM table_a
    ON CONFLICT
    ON CONSTRAINT table_b_pkey DO UPDATE
    SET 
        column_a = CASE 
            WHEN table_b.column_a < EXCLUDED.column_a 
            THEN EXCLUDED.column_a 
            ELSE table_b.column_a END,
        column_b = CASE 
            WHEN table_b.column_b < EXCLUDED.column_b 
            THEN EXCLUDED.column_b 
            ELSE table_b.column_b END