1

I have a postgres SQL query where I want to do upsert. My pk1, pk2 columns are composite primary key. And I want to update 3 columns dk1, dk2, timek if there is a conflict with the primary key constraint. Also when I update the columns on conflict, say timek column, then I need to check if the new value is less than old value and choose accordingly if need to use old value or new value. Here is the query I have but it throws error. I am new to postgres SQL, please suggest what's wrong?

INSERT INTO data_reports (pk1, pk2, dk1, dk2, dk3, timek, valuek)  VALUES (?, ?, ?, ?, ?, ?, ?)  
ON CONFLICT (pk1, pk2) DO UPDATE SET 
dk1 = EXCLUDED.dk1, 
dk2 = CASE WHEN (dk2 < EXCLUDED.dk2) THEN EXCLUDED.dk2 ELSE dk2 END), // I believe dk2 (existing value in DB) is not selected but how to do that
timek = CASE WHEN (timek < EXCLUDED.timek) THEN EXCLUDED.timek ELSE timek END);

2 Answers 2

2
  1. You can refer to pre-update column values by specifying the table name: e.g. data_reports.dk2.
  2. Open and close parentheses, There are 5 (s and 7 )s.
  3. Start a comment with --, or enclose a comment with /* and */.
INSERT INTO data_reports (pk1,pk2,dk1,dk2,dk3,timek,valuek)
VALUES (1,1,9,9,9,9,9)
ON CONFLICT (pk1,pk2) DO
UPDATE
SET
    dk1 = EXCLUDED.dk1,
    dk2 =
    (CASE
        WHEN (data_reports.dk2 < EXCLUDED.dk2) THEN EXCLUDED.dk2
        ELSE data_reports.dk2
    END),
    timek =
    (CASE
        WHEN (data_reports.timek < EXCLUDED.timek) THEN EXCLUDED.timek
        ELSE data_reports.timek
    END);
1
  • Thanks @shoek, was looking for pre-update column values to access. It works! May 19, 2020 at 9:50
1

Just FYI: You could simplify by replacing the CASE expression by the LEAST function:

insert into data_reports (pk1,pk2,dk1,dk2,dk3,timek,valuek)
values (1,1,9,9,9,9,9)
on conflict (pk1,pk2) do
update
set
    dk1 = excluded.dk1,
    dk2 = least(data_reports.dk2, excluded.dk2),
    timek = least(data_reports.timek, excluded.timek); 
1
  • Thanks! @Belayer This is indeed the more better answer, but as per the question I wanted to use the CASE ELSE THEN. :) May 20, 2020 at 16:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.