

- 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 ORDER BY ASC and display NULLs at the bottom?
For this, use CASE statement with ORDER BY. Let us first create a table −
mysql> create table DemoTable1937 ( Name varchar(20) ); Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1937 values('Chris'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1937 values(NULL); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1937 values('Adam'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1937 values('John'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1937 values(''); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1937 values(NULL); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1937 values('Bob'); Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1937;
This will produce the following output −
+-------+ | Name | +-------+ | Chris | | NULL | | Adam | | John | | | | NULL | | Bob | +-------+ 7 rows in set (0.00 sec)
Here is the query to ORDER BY ASC and display NULLs at the bottom:
mysql> select * from DemoTable1937 order by case when Name IS NULL then 100 when Name='' then 101 else 103 end desc , Name asc;
This will produce the following output −
+-------+ | Name | +-------+ | Adam | | Bob | | Chris | | John | | | | NULL | | NULL | +-------+ 7 rows in set (0.00 sec)
- Related Questions & Answers
- Order By date ASC in MySQL?
- MySQL query to display ASC order in number column?
- Implement MySQL ORDER BY without using ASC or DESC?
- MySQL order by 0 first and then display the record in descending order?
- Wrap around to first value and implement MySQL ORDER BY ASC and DESC in a single query
- Select last 3 rows from database order by id ASC?
- Order by a single field and display rest of the records in the same order with MySQL
- MySQL Order by a specific column x and display remaining values in ascending order
- How to ORDER BY DESC and display the first 3 records in MySQL?
- Advanced sorting in MySQL to display strings beginning with J at the end even after ORDER BY
- MySQL ORDER BY CASE to display special character in the beginning
- Displaying only a list of records in ASC order with MySQL
- Order MySQL records randomly and display name in Ascending order
- How to order records by a column in MySQL and place empty records at the end?
- MySQL Order By specific strings?
Advertisements