Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL IFNULL ELSE

I have a select statement where I want to make the select conditional like this:

IFNULL(field_a, field_a, field_b) 

so that it checks field a. If a is null then the select would be field b.

Is that possible ?

like image 219
mcgrailm Avatar asked Jul 09 '10 18:07

mcgrailm


People also ask

What is Ifnull in MySQL?

MySQL IFNULL() Function The IFNULL() function returns a specified value if the expression is NULL. If the expression is NOT NULL, this function returns the expression.

IS NOT NULL in if condition MySQL?

MySQL IFNULL() takes two expressions and if the first expression is not NULL, it returns the first expression. Otherwise, it returns the second expression. Depending on the context in which it is used, it returns either numeric or string value. An expression.

How do I write if else in MySQL?

The syntax for the IF-THEN-ELSE statement in MySQL is: IF condition1 THEN {... statements to execute when condition1 is TRUE...} [ ELSEIF condition2 THEN {...

IS NULL if else SQL?

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


2 Answers

Use COALESCE:

SELECT COALESCE(field_a, field_b) 

COALESCE is an ANSI standard function that returns the first non-null value from the list of columns specified, processing the columns from left to right. So in the example, if field_a is null, field_b value will be displayed. However, this function will return NULL if there is no non-null value from the columns specified.

It's supported on MySQL (I've used it on 4.1), SQL Server (since v2000), Oracle 9i+...

like image 84
OMG Ponies Avatar answered Oct 01 '22 14:10

OMG Ponies


and another way to skin that cat (flexible for not just null comparisons)...

select if(field_a is not null, field_a, field_b) from... 
like image 29
user3590489 Avatar answered Oct 01 '22 12:10

user3590489