Home > Database > Mysql Tutorial > How to Sort NULL Values Last in MySQL ORDER BY Clauses?

How to Sort NULL Values Last in MySQL ORDER BY Clauses?

Patricia Arquette
Release: 2024-12-12 12:26:24
Original
167 people have browsed it

How to Sort NULL Values Last in MySQL ORDER BY Clauses?

Sorting NULL Values Last in MySQL OrderBy Queries

In order to order data effectively in MySQL using the OrderBy clause, it's often necessary to ensure that NULL values are treated consistently. By default, NULL values come before non-NULL values when ordering in ascending order and after them in descending order. This behavior can be problematic when the desired order is to place all non-NULL values before the NULL values.

Achieving "NULLs Last" Ordering

MySQL provides a convenient syntax that allows sorting of NULL values last. To achieve this, precede the column name in the OrderBy clause with a minus sign (-) and switch the sort order to descending (DESC):

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

This syntax essentially inverts the behavior of the DESC keyword, placing the NULL values at the end of the sorted results.

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