views:

42

answers:

3

I have a table of contacts which has name and default_name columns among others.

Contact name is name, unless name=NULL and then it is default_name (which cannot be NULL).

I would like to order my selection by contact name.

For example:

contact_id          name          default_name
----------          ----          ------------
    1               Dave             David
    2                                Misha
    3                                Alex
    4            Brother Leon        Leon

should become:

contact_id          name          default_name
----------          ----          ------------
    3                                Alex
    4            Brother Leon        Leon
    1               Dave             David
    2                                Misha

How would I achieve this ?

+5  A: 

Try

ORDER BY COALESCE(name,default_name)
SQLMenace
Thanks a lot !!
Misha Moroshko
+2  A: 

This will work:

ORDER BY (IF(name IS NOT NULL, name, default_name))

SQLMenace's solution is better. Leaving this in place to show how to use IF() in ORDER clauses.

mySQL Reference: Control Flow Structures

Pekka
Thanks for the link !!
Misha Moroshko
+1  A: 

details differ depending on the DBMS, but the general idea is to ORDER BY IFNULL(name, default_name) for appropriate choice of the function IFNULL. The semantics of IFNULL are that it's the first value unless it's null, and then it's the second value. Most DBMSes know it by about that name.

http://dev.mysql.com/doc/refman/4.1/en/control-flow-functions.html#function_ifnull

Ian
Apparently COALESCE is another name that function goes by.
Ian
+1, better to link 5.1 documentation though - 4.1 is rather dated: http://dev.mysql.com/doc/refman/5.1/en/control-flow-functions.html#function_ifnull
Piskvor
Yes but COALESCE is ANSI standard, ISNULL() is another proprietary one..used by Sybase and SQL Server. Oracle uses nvl()
SQLMenace
Notice: the question tags MYSQL, so a MYSQL answer is suitable.
Ian
@Ian: Yes, but ANSI syntax is generally preferred for sake of portability. There're lots out there who think that SQL is the same on all databases, and are quick to find that's not the case. A `CASE` expression evaluating on each column being null would be the next option after `COALESCE` for this question...
OMG Ponies