

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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)
- Related Questions & Answers
- MySQL query to order by NULL values
- MongoDB order by two fields sum?
- How to ORDER BY grouped fields in MySQL?
- Order MySQL query by multiple ids?
- MySQL query to order by current day and month?
- Can we use ORDER BY NULL in MySQL?
- MySQL query to select distinct order by id
- MySQL Order by a specific column x and display remaining values in ascending order
- Order a MySQL table by two columns?
- Order by a function of two columns in a single MySQL query
- MySQL command to order timestamp values in ascending order?
- How does COALESCE order results with NULL and NON-NULL values?
- Query non-empty values of a row first in ascending order and then display NULL values
- MySQL query to ORDER BY `user_id` IN (1,2,3) AND `name` for custom ordering
- How to ORDER BY FIELD with GROUP BY in a single MySQL query?
Advertisements