The easiest way is to use the VALUES keyword, for example 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 cases, even with columns with zero .
Edit:
The solution with the keyword COALESCE not universal. It has important limitations:
- It will not work if the columns are of type
Date (if you use dates before 01/01/1753 ) - It will not work if one of the columns is
NULL . It interprets the NULL value as the minimum datetime value. But is this really true? It is not even datetime , it is nothing. - An
IF expression will be much more complicated if we use more than two columns.
According to the question:
What is the easiest way to sort this table?
The shortest and simplest solution is the one described above, because:
- It does not require a lot of coding to implement it - just add another line.
- You do not need to worry about whether the columns are nullable or not. You just use the code and it works.
- You can expand the number of columns in a query by simply adding it after the decimal point.
- It works with
Date columns and you do not need to change the code.
Edit 2:
The Zohar Peled proposed the following order:
I would order strings according to these rules: first, when both null, second, when date1 is null, third when date 2 is null, fourth, min (date1, date2)
So, for this case, a solution can be achieved using the same approach as 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 result for this code is below:

COALESCE solution will not sort the table this way. It puts the rows where at least one cell is NULL . His conclusion is as follows:

Hope this helps and awaits critics.