Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return one of two columns in a view - whichever one is not null

I have a table with three columns:

ColumnA          ColumnB         ColumnC
AAA               NULL            123
BBB               222             NULL
CCC               NULL            NULL

I would like to create a SELECT statement which will return ColumnA, and then a second column which will either show the value of ColumnB unless ColumnB is null; otherwise it will show the value of ColumnC, even it it's NULL. Can I use an IF statement for that? Something like:

SELECT ColumnA, 
IF(ColumnB IS NULL, ColumnC, ColumnB)
FROM table

**If I get this working, the next step would be to return the value of a joined column instead of ColumnB. In effect the IF statement would be

IF(table.ColumnB IS NULL, table.ColumnC, table2.ColumnD)
like image 543
morganpdx Avatar asked Mar 04 '11 21:03

morganpdx


People also ask

How do you coalesce multiple columns in SQL?

The coalesce in MySQL can be used to return first not null value. If there are multiple columns, and all columns have NULL value then it returns NULL otherwise it will return first not null value. The syntax is as follows. SELECT COALESCE(yourColumnName1,yourColumnName2,yourColumnName3,.......


1 Answers

Use COALESCE

SELECT ColumnA, COALESCE(ColumnB, ColumnC) as 'Value'

like image 109
JNK Avatar answered Nov 15 '22 05:11

JNK