In Postgres 10 I want to perform an UPDATE twice. First UPDATE should run no matter what, updating the alwaysupdate
column. And the second UPDATE should run only if the SELECT statement below returns a row count of 0, which means sometimesupdate
should get updated only if all of the rows in mytable
where mykey = 100
have sometimesupdate
set to null
.
-- Run no matter what, updating 'alwaysupdate'
update mytable set alwaysupdate = now() where keyA = 100 and keyB = 200
-- Check the number of rows where 'sometimesupdate' has a value
select count(*) from mytable where keyB = 200 and sometimesupdate is not null
-- If 'sometimesupdate' is null for all rows above, give it a value in this row
update mytable set sometimesupdate = now() where keyA = 100 and keyB = 200
What's the most efficient way to do this? Is it possible to combine it into a single SQL statement? Otherwise multiple statements wrapped in a transaction? Otherwise a function if necessary.