Home > Database > Mysql Tutorial > How to Sort MySQL Results with NULL Values Last?

How to Sort MySQL Results with NULL Values Last?

Linda Hamilton
Release: 2024-12-09 00:29:09
Original
1027 people have browsed it

How to Sort MySQL Results with NULL Values Last?

How to Order MySQL Results with Null Values Last

When ordering MySQL results with a numeric column, null values can be problematic as they are treated as zero. This can lead to unexpected ordering, where null values appear before non-null values.

To address this issue, MySQL offers an undocumented syntax that allows you to sort null values last. This is achieved by placing a minus sign (-) before the column name and switching the ASC to DESC:

SELECT * FROM tablename WHERE visible=1 ORDER BY -position DESC, id DESC
Copy after login

This syntax essentially inverts the position DESC ordering, placing null values last while maintaining the same ordering for non-null values.

For example, if you have the following data:

NULL, NULL, NULL, 1, 2, 3, 4
Copy after login
Copy after login

Using the standard ORDER BY position ASC, id DESC statement would result in:

NULL, NULL, NULL, 1, 2, 3, 4
Copy after login
Copy after login

However, using the -position DESC syntax would produce the desired ordering:

1, 2, 3, 4, NULL, NULL, NULL
Copy after login

This undocumented syntax provides a convenient way to ensure that null values are sorted last in MySQL results. It is important to note that this is not a standard SQL feature and may not be supported in all database systems.

The above is the detailed content of How to Sort MySQL Results with NULL Values Last?. 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