Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SELECT one column if the other is null

Tags:

sql

mysql

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)

like image 652
James Avatar asked Apr 18 '11 02:04

James


People also ask

How do you check if columns have NULL values?

Multiple Solutions (Column Contains Some NULLs | Column is All NULLs * Test Single Column | Test Multiple Columns with Tabular Results) Where the result is 0, there are no NULLs. Where the result is 0, the column is entirely made up of NULLs.

Is NULL in select statement?

Description. The IS NULL condition is used in SQL to test for a NULL value. It returns TRUE if a NULL value is found, otherwise it returns FALSE. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.


2 Answers

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.

like image 77
OMG Ponies Avatar answered Oct 02 '22 03:10

OMG Ponies


Use a CASE statement for the select.

SELECT CASE WHEN a2.date IS NULL THEN a1.date     ELSE a2.date END AS mydate 
like image 30
Rasika Avatar answered Oct 02 '22 03:10

Rasika