0

Is there a better way to write this query in a plpgsql function than almost duplicating the query twice? Any way to say if valB is null then it should match anything in colB, essentially being removed from the where clause?

if (valB is not null) then
    update mytable set colA = valA where (colB, colC) = (valB, valC);
else
    update mytable set colA = valA where (colC) = (valC);
end if;

2 Answers 2

1

You can use an OR condition with the parameter:

update mytable 
   set colA = valA 
where (valb is null and colC = valC)
   or (valb is not null and (colb, colc) = (valb, valc));
Sign up to request clarification or add additional context in comments.

Comments

1

You can use or. I would phrase this as:

update mytable 
   set colA = valA 
where colC = valC and
       (valb is null or colb = valb);

2 Comments

Would you say there's any practical difference between what you suggested and modifying it slightly, replacing (valb is null or colb = valb) with (colb = case when valb is null then colb else valb end) or are they identical? Does the other way have any downsides in terms of performance or anything else (apart from being a bit longer to read)?
@user779159 . . . I prefer leaving case expressions out of where clauses.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.