I'm trying to select the max date in three different fields in each record (MySQL) So, in each row, I have date1, date2 and date3: date1 is always filled, date2 and date3 can be NULL or empty The GREATEST statement is simple and concise but has no effects on NULL fields, so this doesn't work well:
SELECT id, GREATEST(date1, date2, date3) as datemax FROM mytable
I tried also more complex solutions like this:
SELECT CASE WHEN date1 >= date2 AND date1 >= date3 THEN date1 WHEN date2 >= date1 AND date2 >= date3 THEN date2 WHEN date3 >= date1 AND date3 >= date2 THEN date3 ELSE date1 END AS MostRecentDate
Same problem here: NULL values are a GREAT problem in returning the right records
Please, have you got a solution? Thanks in advance....
MAX ignores any null values. MAX returns NULL when there is no row to select.
If you want to understand VALUE try this query which creates a virtual 1 column table: SELECT * FROM (VALUES (1), (5), (1)) as listOfValues(columnName) And this query which creates a virtual 2 column table: SELECT * FROM (VALUES (1,2), (5,3), (1,4)) as tableOfValues(columnName1, ColumnName2) Now you can understand why ...
The MySQL COALESCE() function is used for returning the first non-null value in a list of expressions. If all the values in the list evaluate to NULL, then the COALESCE() function returns NULL. The COALESCE() function accepts one parameter which is the list which can contain various values.
Use COALESCE
SELECT id, GREATEST(date1, COALESCE(date2, 0), COALESCE(date3, 0)) as datemax FROM mytable
Update: This answer previously used IFNULL
which does work, but as Mike Chamberlain pointed out in the comments, COALESCE
is actually the preferred method.
If date1
can never be NULL
, then the result should never be NULL
, right? Then you could use this, if you want NULL
dates be not counted in the calculations (or change the 1000-01-01
to 9999-12-31
, if you want Nulls to count as the "end of time"):
GREATEST( date1 , COALESCE(date2, '1000-01-01') , COALESCE(date3, '1000-01-01') ) AS datemax
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With