Sorting NULL Values to Last in Ascending Order
Sorting a SQL table by a datetime field that may contain NULL values can be problematic if you want the NULL values to appear at the end of the sorted results instead of the beginning.
To achieve this, you can use the following technique:
select MyDate from MyTable order by case when MyDate is null then 1 else 0 end, MyDate
In this query, the CASE expression evaluates to 1 for NULL values in the MyDate field and 0 for non-NULL values. When sorting in ascending order, the rows with a higher evaluation value (1 for NULL) will appear later in the sorted list. Therefore, the NULL values will be placed at the end of the sorted results.
The above is the detailed content of How to Sort NULL Datetime Values to the End in Ascending Order in SQL?. For more information, please follow other related articles on the PHP Chinese website!