![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MySQL query to order by two fields and NULL values in chronological order?
Let us first create a table −
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;
Output
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);
Output
This will produce the following output −
+-----------+----------+ | FirstName | LastName | +-----------+----------+ | David | Taylor | | Mike | NULL | | Sam | Brown | | NULL | Smith | +-----------+----------+ 4 rows in set (0.04 sec)
Advertisements