MySQL ORDER BY ASC and display NULLs at the bottom?

MySQLMySQLi Database

For this, use CASE statement with ORDER BY. Let us first create a table −

mysql> create table DemoTable1937
   (
   Name varchar(20)
   );
Query OK, 0 rows affected (0.00 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1937 values('Chris');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1937 values(NULL);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1937 values('Adam');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1937 values('John');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1937 values('');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1937 values(NULL);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1937 values('Bob');
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1937;

This will produce the following output −

+-------+
| Name  |
+-------+
| Chris |
| NULL  |
| Adam  |
| John  |
|       |
| NULL  |
| Bob   |
+-------+
7 rows in set (0.00 sec)

Here is the query to ORDER BY ASC and display NULLs at the bottom:

mysql> select * from DemoTable1937
   order by case when Name IS NULL then 100
   when Name='' then 101
   else 103
   end desc
   ,
   Name asc;

This will produce the following output −

+-------+
| Name  |
+-------+
| Adam  |
| Bob   |
| Chris |
| John  |
|       |
| NULL  |
| NULL  |
+-------+
7 rows in set (0.00 sec)
raja
Published on 30-Dec-2019 12:23:00
Advertisements