I have a table with 5 columns.
- id
- bday
- update
- restartDate
- startDate
I need to update each rows update column with the most recent date between restartDate and startDate
I’ve tried:
update mytable
set update = (select MAX(v)from (values (restartDate),(startDate)) as value(v))
But that seems to make the update column current date(like now())
I should also mention that the startDate and restartDate can be null
For example:
restartDate | startDate | update |
---|---|---|
2022-11-11 | null | null |
would set update as 2022-11-11
or
restartDate | startDate | update |
---|---|---|
2022-11-01 | 2022-11-05 | null |
would set update as 2022-11-05
restartDate cannot be null
2
Answers
You can use
CASE
for conditions.You can use
GREATEST
for that:This will already be sufficient if you use Postgres as you said.
Otherwise, if you use MariaDB or MYSQL, you will notice the column "updated" will be null if your startDate is null because their
GREATEST
doesn’t handle that. In this case, you can add aCOALESCE
:You can verify it’s working correctly here: db<>fiddle
As you can also verify there is that the update command you’ve already mentioned is working, too.