I use SQL Server 2008 R2
.
I need to sort a table by the minimal value of two columns.
The table looks like this:
ID: integer;
Date
Use a CASE
expression in the ORDER BY
:
ORDER BY case when date1 < date2 then date1 else date2 end
Edit:
If null values need to be considered, add coalesce()
:
ORDER BY case when date1 < date2 then date1 else coalesce(date2,date1) end
Explanation:
If date1 < date2 then order by date1. (Both dates are non null here.) Works just like before.
Else use COALESCE()
to order by date2 (when date2 is not null), or date1 (when date2 is null), or by null (if both dates are null.)