views:

49

answers:

2
+1  Q: 

mysql IFNULL ELSE

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

IFNULL(field_a,field_a,feild_b)

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

is that possible ?

+6  A: 

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+...

OMG Ponies
I support the use of COALESCE as well.
treefrog
+1 - I like that one! Not heard of it before, definitely useful.
Dave Rix
+3  A: 

Yes, but it's just two parameters:

IFNULL(field_a,field_b)

If field_a is not null, it will be returned. Otherwise field_b will be returned.

Reference: IFNULL

Matt
+1: For answering the OP's question, but I'd rather use ANSI functions when possible.
OMG Ponies