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

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

Imagine that you need sort records by lowest value of either one of two columns. Some databases could use a non-aggregated MIN() or LEAST() function for this (... ORDER BY MIN(Date1, Date2)), but in standard SQL, you have to use 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

IdDate1Date2
12017-01-012017-01-31
22017-01-312017-01-03
32017-01-312017-01-02
42017-01-062017-01-31
52017-01-312017-01-05
62017-01-042017-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

IdDate1Date2
12017-01-012017-01-31
32017-01-312017-01-02
22017-01-312017-01-03
62017-01-042017-01-31
52017-01-312017-01-05
42017-01-062017-01-31

Explanation

As you see row with Id = 1 is first, that because Date1 have lowest record from entire table 2017-01-01, row where Id = 3 is second that because Date2 equals to 2017-01-02 that is second lowest value from table and so on.

So we have sorted records from 2017-01-01 to 2017-01-06 ascending and no care on which one column Date1 or Date2 are those values.



Got any SQL Question?