How to implement MySQL ORDER BY x where (x=col3 if col3!=null, else x=col2)?


For this, you can use ORDER BY IFNULL(). Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Name varchar(20),
   -> CountryName varchar(20)
   -> );
Query OK, 0 rows affected (0.61 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('Chris',NULL);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values('David','AUS');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(NULL,'UK');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values(NULL,'AUS');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(NULL,NULL);
Query OK, 1 row affected (0.11 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-------+-------------+
| Name  | CountryName |
+-------+-------------+
| Chris | NULL        |
| David | AUS         |
| NULL  | UK          |
| NULL  | AUS         |
| NULL  | NULL        |
+-------+-------------+
5 rows in set (0.00 sec)

Here is the query to implement MySQL ORDER BY x where (x=col3 if col3!=null, else x=col2) −

mysql> select *from DemoTable
   -> order by ifnull(Name,CountryName);

This will produce the following output −

+-------+-------------+
| Name  | CountryName |
+-------+-------------+
| NULL  | NULL        |
| NULL  | AUS         |
| Chris | NULL        |
| David | AUS         |
| NULL  | UK          |
+-------+-------------+
5 rows in set (0.00 sec)

Updated on: 17-Dec-2019

45 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements