I want to update data using query but when column is not null, it will not update and still use old data. I tried with this query but failed.
UPDATE tableA SET
column2 = case column2 WHEN NULL THEN to_timestamp('2022-08-09 13:57:40', 'YYYY-MM-DD hh24:mi:ss') end,
column3 = CASE column3 WHEN NULL THEN to_timestamp('2022-08-09 13:57:40', 'YYYY-MM-DD hh24:mi:ss') end,
colum3 = '1'
WHERE column1='abc';
2
Answers
to check for
NULL
you needIS NULL
Alternatively, you can use coalesce:
And a word of advice (reflected in the suggestion above)… evaluating an expression is "cheaper" than doing actual DML, so I’d encourage you to consider, where possible, adding a
where
clause to determine if it’s even worth updating or not.Postgres uses MVCC, which will essentially kill the original row and create a new row with the modified data. If you’re doing this on tens of thousands of rows, it can make a lot of sense to limit those transactions.
In part this comes down to knowing your data, but I think it’s generally worthwhile limit updates to those that need to happen.