CASE in ORDER BY clause to sort records by lowest value of 2 columns

suggest change

Imagine that you need to sort records by the lower of two columns. Some databases can use a non-aggregated MIN() or LEAST() function for this (... ORDER BY LEAST(Date1, Date2)), but standard SQL uses a CASE expression.

The CASE expression in the query below looks at the Date1 and Date2 columns, checks which column has the lower value, and sorts the records depending on this value.

Sample data

Id | Date1 | Date2 |
—— | —— | —— |
1 | 2017-01-01| 2017-01-31|
2 | 2017-01-31| 2017-01-03|
3 | 2017-01-31| 2017-01-02|
4 | 2017-01-06| 2017-01-31|
5 | 2017-01-31| 2017-01-05|
6 | 2017-01-04| 2017-01-31|

Query

SELECT Id, Date1, Date2
FROM YourTable
ORDER BY CASE 
           WHEN COALESCE(Date1, '1753-01-01') < COALESCE(Date2, '1753-01-01') THEN Date1 
           ELSE Date2 
         END

Results

|Id | Date1 | Date2 | | —— | —— | —— | |1 |2017-01-01| 2017-01-31 | |3 | 2017-01-31 |2017-01-02| |2 | 2017-01-31 |2017-01-03| |6 |2017-01-04| 2017-01-31 | |5 | 2017-01-31 |2017-01-05| |4 |2017-01-06| 2017-01-31 |

Explanation

As you can see, the row with Id = 1 is first because Date1 holds the lowest value in the table, 2017-01-01. The row with Id = 3 is second because Date2 is 2017-01-02, the second-lowest value, and so on.

The rows are sorted from 2017-01-01 through 2017-01-06, regardless of whether that value is in Date1 or Date2. The sentinel '1753-01-01' is the lower bound of the SQL Server datetime type; use a sentinel that is valid for your column type. The sample rows have no NULLs, so the sentinel is not used here.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents