Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partial update based on condition in postgres

Tags:

postgresql

I would like to make an update to a table, and the columns updated is dependent on a condition. I already know how to make a conditional WHERE clause like so:

UPDATE table SET colA='apple', colB='banana' WHERE colC='fruits

However I would like to base the update on a condition, such that if the conditional is false, only colA will update. Something to the extent of the following:

UPDATE table SET colA='apple', (if $1=true colB='banana') WHERE colC='fruits

The only resources I'm finding are pertaining to the first example. Is this possible in Postgres? I would like to avoid making separate queries for this type of condition.

like image 897
anesthetic Avatar asked Apr 12 '26 20:04

anesthetic


2 Answers

You could use CASE expressions to control the logic of updating the B column:

UPDATE table
SET
    colA = 'apple',
    colB = CASE WHEN $1 = true THEN 'banana' ELSE colB END
WHERE
    colC = 'fruits';

When the $1 flag be set to true, the B column would be updated to banana, otherwise the update would just set to the current value, which is effectively a no-op.

like image 54
Tim Biegeleisen Avatar answered Apr 15 '26 19:04

Tim Biegeleisen


A CASE statement might help you here:

UPDATE table
SET colA = 'apple',
    colB = CASE WHEN $1 = true THEN 'banana' ELSE colB END
WHERE colC = 'fruits';

However, there may be risk of SQL injection, in which case you may be better off having two separate queries, selected by your application logic.

like image 36
richyen Avatar answered Apr 15 '26 19:04

richyen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!