I want to implement following logic in my SQL query:
If some date is not set or it’s year is 1970 then select real_date flag to null AND change date to current data, else – real_date is true and no need to change date.
real_date is not an actual field in the table but a flag I need to set up.
I can easily do this using 2 lines in my SELECT section:
, IF (actualDate is NULL OR YEAR(actualDate) = 1970, CURRENT_TIMESTAMP(), actualDate) as actual_date
, IF (actualDate is NULL OR YEAR(actualDate) = 1970, null, true) as real_date
And the question – is it the only way to do it? Don’t really like the fact that I had to copy condition again. Can somehow the second select be moved to the first one?
Update: I need to select both actualDate (it will be either fixed to current time version or the actual stored value) and real_date (which will be true or false/null). Maybe I am missing something, but how could COALESCE function help here?
Update 2: Thanks again everyone. Learnt other ways to write it but all of them have check in 2 places. My idea was to have logical condition in only one place but doesn’t seem to be possible.
Your variant is pretty and comfortable for supporting code in future, do not change anything.