Question

We have an UPSERT feature achieved through on conflict do set. How can I set the values conditionally in the set statement, like

if(excluded.col1 is null) col1=table.col1 else col1=excluded.col1

We are using Postgres 9.5.

Was it helpful?

Solution

...
SET   col1 = COALESCE(excluded.col1, table.col1)
...

Of course, both tables must be visible.

If you are updating table1 and that's the only change you make it's much more efficient to use a WHERE clause:

...
SET   col1 = excluded.col1
WHERE excluded.col1 IS NOT NULL
AND   excluded.col1 IS DISTINCT FROM table1.col1 -- to avoid empty updates
...

About the added second condition:

Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top