
- Learn MySQL
- MySQL - Home
- MySQL - Introduction
- MySQL - Installation
- MySQL - Administration
- MySQL - PHP Syntax
- MySQL - Connection
- MySQL - Create Database
- MySQL - Drop Database
- MySQL - Select Database
- MySQL - Data Types
- MySQL - Create Tables
- MySQL - Drop Tables
- MySQL - Insert Query
- MySQL - Select Query
- MySQL - Where Clause
- MySQL - Update Query
- MySQL - Delete Query
- MySQL - Like Clause
- MySQL - Sorting Results
- MySQL - Using Join
- MySQL - NULL Values
- MySQL - Regexps
- MySQL - Transactions
- MySQL - Alter Command
- MySQL - Indexes
- MySQL - Temporary Tables
- MySQL - Clone Tables
- MySQL - Database Info
- MySQL - Using Sequences
- MySQL - Handling Duplicates
- MySQL - SQL Injection
- MySQL - Database Export
- MySQL - Database Import
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 Articles
- MySQL query to order by NULL values
- How to ORDER BY grouped fields in MySQL?
- MongoDB order by two fields sum?
- MySQL query to order by current day and month?
- Can we use ORDER BY NULL in MySQL?
- Order MySQL query by multiple ids?
- MySQL query to select distinct order by id
- Query non-empty values of a row first in ascending order and then display NULL values
- Order by a function of two columns in a single MySQL query
- MySQL Order by a specific column x and display remaining values in ascending order
- MySQL command to order timestamp values in ascending order?
- How does COALESCE order results with NULL and NON-NULL values?
- MySQL query to ORDER BY `user_id` IN (1,2,3) AND `name` for custom ordering
- Maintaining order in MySQL “IN” query?
- Order a MySQL table by two columns?

Advertisements