Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SELECT not null column from two columns

Tags:

sql

null

mysql

I have a table that has two columns, one of which will be NULL and one will not, what I would like to do is something like:

SELECT (column1 OR column2) AS value

But I need to retrieve the value that is not null. I feel like this is probably an easy question, but any help is appreciated.

like image 310
The Thirsty Ape Avatar asked Nov 21 '12 04:11

The Thirsty Ape


2 Answers

SELECT COALESCE(column1, column2) AS value

or

SELECT IFNULL(column1, column2) AS value

or

SELECT CASE WHEN column1 IS NOT NULL THEN column1 ELSE column2 END AS value

or

SELECT IF(column1 IS NOT NULL, column1, column2) AS value
like image 156
zerkms Avatar answered Nov 05 '22 23:11

zerkms


In mysql, you can use the IFNULL function. In SQL Server, you can use ISNULL function.

like image 39
Carlisle18 Avatar answered Nov 06 '22 01:11

Carlisle18