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
The simplest way is using of the VALUES keyword, like the following:
SELECT ID, Date1, Date2
FROM YourTable
ORDER BY (SELECT MIN(v) FROM (VALUES (Date1), (Date2)) AS value(v))
This code will work for all the cases, even with nullable columns.
Edit :
The solution with the COALESCE
keyword is not universal. It has the important restrictions:
Date
type (if you use the dates before 01/01/1753
)NULL
. It interprets the
NULL
value as the minimal datetime
value. But is it actually
true? It isn't even datetime
, it is nothing. IF
expression will be much more complicated if we use more than two columns.According to the question:
What is the simplest way to sort this table that way?
The shortest and the simplest solution is the one which described above, because:
Date
columns and you don't need to modify the code.Edit 2 :
Zohar Peled suggested the following way of order:
I would order the rows by this rules: first, when both null, second, when date1 is null, third, when date 2 is null, fourth, min(date1, date2)
So, for this case the solution can be reached by using of the same approach, like the following:
SELECT ID, Date1, Date2
FROM YourTable
ORDER BY
CASE WHEN Date1 IS NULL AND Date2 IS NULL THEN 0
WHEN Date1 IS NULL THEN 1
WHEN Date2 IS NULL THEN 2
ELSE 3 END,
(SELECT MIN(v) FROM (VALUES ([Date1]), ([Date2])) AS value(v))
The output for this code is below:
The COALESCE
solution will not sort the table this way. It messes up the rows where at least one cell of the NULL
value. The output of it is the following:
Hope this helps and waiting for critics.