Search code examples
mysqlsqlnullcoalesce

How to get the minimum date of several columns, excluding nulls?


insert into table (col1, col2, col3, col4) values ('2015-01-01','2014-01-01', NULL, '2013-01-01')

I am looking for a function like this:

select least_but_no_nulls(col1, col2, col3, col4) from table

result: '2013-01-01'

How can I get the minimum date of several columns, excluding nulls?


Solution

  • Alas, least() now returns NULL if any arguments are NULL. You can use a giant coalesce:

    select least(coalesce(col1, col2, col3, col3),
                 coalesce(col2, col3, col4, col1),
                 coalesce(col3, col4, col1, col2),
                 coalesce(col4, col1, col2, col3)
                )
    

    Or, you can use some unlikely value in the future and nullif():

    select nullif(least(coalesce(col1, '9999-01-01'),
                        coalesce(col2, '9999-01-01'),
                        coalesce(col3, '9999-01-01'),
                        coalesce(col4, '9999-01-01'),
                       ), '9999-01-01'
                 )