MySQL: get MAX or GREATEST of several columns, but with NULL fields

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

COALESCE your date columns before you use them in GREATEST.

The way you handle them will depend on how you want to deal with NULL.. either high or low?