Home > Database > Mysql Tutorial > How Can I Sort MySQL Data with NULL Values at the End?

How Can I Sort MySQL Data with NULL Values at the End?

Mary-Kate Olsen
Release: 2024-12-09 03:32:13
Original
584 people have browsed it

How Can I Sort MySQL Data with NULL Values at the End?

MySQL NULL Filtering and Sorting

When ordering data in MySQL using ORDER BY, null values are treated as 0, causing inconsistencies in desired ordering. To address this issue, consider using a special syntax to force nulls to the end of the sorted list.

To sort values in ascending order and place nulls at the end, use the following syntax:

ORDER BY -position DESC
Copy after login

This reverses the default ASC ordering for the position column, effectively treating null values as the highest value. By combining this with a DESC ordering for the id column, you can achieve the desired ordering:

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

This will result in the following ordering:

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

Remember that this syntax is undocumented in MySQL and may not be available in all versions. For a comprehensive reference, refer to the MySQL documentation on ORDER BY with additional flags.

The above is the detailed content of How Can I Sort MySQL Data with NULL Values at the End?. 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