SELECT one column if the other is null

MysqlSql

Mysql Problem Overview


I want to select a2.date if it's there, but if it's NULL I want to select a1.date (a2 is being left-joined). This:

SELECT a2.date OR a1.date
       ...

Simply returns a boolean result (as one would expect), how do I get the actual value of the non-null column though? (a2.date is preferred, but if it's null then a1.date)

Mysql Solutions


Solution 1 - Mysql

The ANSI means is to use COALESCE:

SELECT COALESCE(a2.date, a1.date) AS `date`
   ...

The MySQL native syntax is IFNULL:

SELECT IFNULL(a2.date, a1.date) AS `date`
   ...

Unlike COALESCE, IFNULL is not portable to other databases.

Another ANSI syntax, the CASE expression, is an option:

SELECT CASE
         WHEN a2.date IS NULL THEN a1.date
         ELSE a2.date
       END AS `date`
   ...

It requires more direction to work properly, but is more flexible if requirements change.

Solution 2 - Mysql

Use a CASE statement for the select.

SELECT CASE WHEN a2.date IS NULL THEN a1.date
    ELSE a2.date END AS mydate

Solution 3 - Mysql

Check out the COALESCE function.

Takes a variable number of arguments and returns the first non-null one. It works fine with joins.

Solution 4 - Mysql

SELECT COALESCE(a2.date, a1.date) ...

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJamesView Question on Stackoverflow
Solution 1 - MysqlOMG PoniesView Answer on Stackoverflow
Solution 2 - MysqlRasikaView Answer on Stackoverflow
Solution 3 - MysqldkretzView Answer on Stackoverflow
Solution 4 - MysqlpilcrowView Answer on Stackoverflow