Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL order by two different (possibly null) columns

I have a table with three columns; the first column contains IDs and the other two columns contain dates (where at most one is null, but I don't think this should affect anything). How would I go about ordering the IDs based on which date is larger? I've tried

ORDER BY CASE
WHEN date1 > date2 THEN date1
ELSE date2
END

but this didn't work. Can anyone help me? Also, all of the similar problems that I've seen others post have it so that the query sorts the results based on the first column, and then if the first column is null, the second column. Would I first have to define every single null value? I'm creating this table by a full outer join, so that would be an entirely different question to ask, so hopefully it can be done with null values.

like image 750
Gabe C. Avatar asked Mar 12 '12 02:03

Gabe C.


1 Answers

I believe your problem is related to the comparison failing when either column is NULL. So, you probably need:

 ORDER BY CASE
          WHEN date1 IS NULL THEN date2
          WHEN date2 IS NULL THEN date1
          WHEN date1 > date2 THEN date1
          ELSE                    date2
          END
like image 130
Jonathan Leffler Avatar answered Nov 09 '22 06:11

Jonathan Leffler