MySQL query to order by two fields and NULL values in chronological order?


Let us first create a table &miuns;

mysql> create table DemoTable
   -> (
   -> FirstName varchar(100),
   -> LastName varchar(100)
   -> );
Query OK, 0 rows affected (1.39 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('Sam','Brown');
Query OK, 1 row affected (0.25 sec)

mysql> insert into DemoTable values(null,'Smith');
Query OK, 1 row affected (0.16 sec)

mysql> insert into DemoTable values('David','Taylor');
Query OK, 1 row affected (0.22 sec)

mysql> insert into DemoTable values('Mike',null);
Query OK, 1 row affected (0.45 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-----------+----------+
| FirstName | LastName |
+-----------+----------+
| Sam       | Brown    |
| NULL      | Smith    |
| David     | Taylor   |
| Mike      | NULL     |
+-----------+----------+
4 rows in set (0.06 sec)

Here is the query to order by two fields and possibly NULL values in chronological order −

mysql> select *from DemoTable order by coalesce(FirstName,LastName);

This will produce the following output −

+-----------+----------+
| FirstName | LastName |
+-----------+----------+
| David     | Taylor   |
| Mike      | NULL     |
| Sam       | Brown    |
| NULL      | Smith    |
+-----------+----------+
4 rows in set (0.04 sec)
raja
Published on 10-Jul-2019 17:35:36
Advertisements