0

Is it possible to sort this way?

Unsorted

TIMEIN                TIMEOUT
null                  6/19/2014 12:00:00
6/19/2014 08:30:00    6/19/2014 10:30:00
6/19/2014 13:00:00    null
6/19/2014 19:06:00    6/19/2014 20:36:00 

Sorted

TIMEIN                TIMEOUT
6/19/2014 08:30:00    6/19/2014 10:30:00
null                  6/19/2014 12:00:00
6/19/2014 13:00:00    null
6/19/2014 19:06:00    6/19/2014 20:36:00 

The list is sorted by TIMEIN descending. If TIMEIN is NULL, TIMEOUT will be the basis in sorting without reordering 'TIMEIN desc'.

rechie
  • 2,139
  • 5
  • 25
  • 38

2 Answers2

3
ORDER BY IFNULL(TIMEIN, TIMEOUT) DESC
shmosel
  • 49,289
  • 6
  • 73
  • 138
2

There's a handy function called COALESCE in MySQL you can just drop into the ORDER BY clause.

Here is the doc for it
Here is an example

And here is what you can append to your SQL:

ORDER BY COALESCE(TIMEIN, TIMEOUT) DESC
Community
  • 1
  • 1
Kodlee Yin
  • 1,089
  • 5
  • 10
  • 2
    After posting this answer and looking over @shmsel's answer, I looked up the difference between the two and it seems like `IFNULL` is slightly faster than `COALESCE`. http://stackoverflow.com/questions/4747877/mysql-ifnull-vs-coalesce-which-is-faster – Kodlee Yin Jun 25 '14 at 03:38