MySQL | Change the Sort Order of NULL Values
When sorting with the ORDER BY clause, rows whose value is NULL may appear at the top.
This article explains how to handle that case.
Syntax
SELECT "field"
FROM "table_name"
ORDER BY "field" IS NULL [ASC|DESC]
Example
store_information Table
| region_name | store_name | sales |
|---|---|---|
| West | Los Angeles | 1500 |
| West | San Diego | 250 |
| West | Los Angeles | |
| East | Boston | 700 |
SQL Example: NULL Is Sorted First
Assume the table above exists. If you write and run the following SQL statement:
SELECT store_name, sales
FROM store_information
ORDER BY sales ASC
the NULL value is sorted to the top as shown below.
| store_name | sales |
|---|---|
| Los Angeles | NULL |
| San Diego | 250 |
| Boston | 700 |
| Los Angeles | 1500 |
SQL Example: Sort NULL Last
To sort NULL values last, write and run the following SQL statement.
SELECT store_name, sales
FROM store_information
ORDER BY sales IS NULL ASC, sales ASC
The NULL value is sorted to the bottom as shown below.
| store_name | sales |
|---|---|
| San Diego | 250 |
| Boston | 700 |
| Los Angeles | 1500 |
| Los Angeles | NULL |