MySQL Order by with case?


For this, use order by nullif(). Let us first create a table −

mysql> create table DemoTable672(
   CustomerId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   CustomerName varchar(100),
   CustomerAmount int
);
Query OK, 0 rows affected (0.81 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable672(CustomerName,CustomerAmount) values('Chris',560);
Query OK, 1 row affected (0.51 sec)
mysql> insert into DemoTable672(CustomerName,CustomerAmount) values('Robert',null);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable672(CustomerName,CustomerAmount) values('',450);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable672(CustomerName,CustomerAmount) values('David',456);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable672(CustomerName,CustomerAmount) values('Carol',786);
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable672;

This will produce the following output −

+------------+--------------+----------------+
| CustomerId | CustomerName | CustomerAmount |
+------------+--------------+----------------+
| 1          | Chris       | 560             |
| 2          | Robert      | NULL            |
| 3          |             | 450             |
| 4          | David       | 456             |
| 5          | Carol       | 786             |
+------------+--------------+----------------+
5 rows in set (0.00 sec)

Following is how you can perform MySQL order by with case. Here, we have also used FIELD() for case-insensitive search −

mysql> select *from DemoTable672 ORDER BY NULLIF(CustomerName,'') IS NULL, FIELD(CustomerAmount,560,786,450,456);

This will produce the following output −

+------------+--------------+----------------+
| CustomerId | CustomerName | CustomerAmount |
+------------+--------------+----------------+
| 2          | Robert       | NULL           |
| 1          | Chris        | 560            |
| 5          | Carol        | 786            |
| 4          | David        | 456            |
| 3          |              | 450            |
+------------+--------------+----------------+
5 rows in set (0.04 sec)

Updated on: 26-Aug-2019

227 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements