Home > Database > Mysql Tutorial > How to Sort SQL NULL Values to the End of an Ascending Order List?

How to Sort SQL NULL Values to the End of an Ascending Order List?

Mary-Kate Olsen
Release: 2025-01-05 22:36:47
Original
318 people have browsed it

How to Sort SQL NULL Values to the End of an Ascending Order List?

Sorting SQL Null Values at the End in Ascending Order

When working with SQL tables that contain datetime fields, it's often desirable to sort the results in ascending order while prioritizing non-null values. However, by default, null values appear at the beginning of sorted ascending lists.

To overcome this, you can leverage a conditional expression to assign a higher priority to non-null values during sorting. Here's a simple solution:

select MyDate
from MyTable
order by case when MyDate is null then 1 else 0 end, MyDate
Copy after login

This query assigns the value 1 to null datetime values and 0 to non-null values. The CASE statement serves as a CASE expression that prioritizes non-null values during sorting. As a result, non-null values appear before null values in the sorted ascending list.

By utilizing this technique, you can effectively order your SQL results ascendingly, placing null values at the end of the list, ensuring that meaningful data takes precedence in your analysis and presentation.

The above is the detailed content of How to Sort SQL NULL Values to the End of an Ascending Order List?. 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