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.
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;
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!