MySQL IFNULL ELSE

107,248

Solution 1

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

Solution 2

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

Solution 3

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

Share:
107,248
mcgrailm
Author by

mcgrailm

Hello, thanks for visiting my profile. I am a web developer at PSU. I started my carrier by learning applescript. Since then I've become familiar with PHP MySQL, javascript, jQuery as well. I have made use of other services that go hand and hand with those languages such as json,jsonp,ajax. I have some shell scripting experience and have dabbled in perl. Hopefully I have helped you with a question you or maybe you have help me with a question, thanks for stopping by.

Updated on July 08, 2022

Comments

  • mcgrailm
    mcgrailm almost 2 years

    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 ?

  • Chuck Callebs
    Chuck Callebs almost 14 years
    I support the use of COALESCE as well.
  • Apolo
    Apolo over 9 years
    Best answer. Allow to do Select if(name is not null, CONCAT('name is : ',name),'');
  • Andrew
    Andrew over 8 years
    Such a clear explanation of how the function works... Thanks! Updated the broken link.
  • Arda
    Arda over 8 years
    select IFNULL(column, 'default') also works. See here: sqlfiddle.com/#!9/14b752/1/0
  • TommyAutoMagically
    TommyAutoMagically almost 4 years
    Pretty cool explanation of a function I'm not familiar with! However, for OP's question, using IF() is much more readable.