rechie
rechie

Reputation: 2209

MySQL Conditional Ordering

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

Upvotes: 0

Views: 66

Answers (2)

Kodlee Yin
Kodlee Yin

Reputation: 1089

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

Upvotes: 2

shmosel
shmosel

Reputation: 50716

ORDER BY IFNULL(TIMEIN, TIMEOUT) DESC

Upvotes: 3

Related Questions