Home > Database > Mysql Tutorial > How to Sort NULL Datetime Values to the End in Ascending Order in SQL?

How to Sort NULL Datetime Values to the End in Ascending Order in SQL?

Mary-Kate Olsen
Release: 2025-01-06 00:31:39
Original
194 people have browsed it

How to Sort NULL Datetime Values to the End in Ascending Order in SQL?

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template