![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 timestamp in descending order but place the timestamp 0000-00-00 00:00:00 first?
Let us first create a table &mnus;
mysql> create table DemoTable ( `timestamp` timestamp ); Query OK, 0 rows affected (1.12 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(now()); Query OK, 1 row affected (0.27 sec) mysql> insert into DemoTable values('00:00:00'); Query OK, 1 row affected (0.73 sec) mysql> insert into DemoTable values('2018-01-10 12:34:45'); Query OK, 1 row affected (0.80 sec) mysql> insert into DemoTable values('2019-12-31 10:50:45'); Query OK, 1 row affected (0.84 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+---------------------+ | timestamp | +---------------------+ | 2019-08-17 06:17:12 | | 0000-00-00 00:00:00 | | 2018-01-10 12:34:45 | | 2019-12-31 10:50:45 | +---------------------+ 4 rows in set (0.00 sec)
Following is the query to order the timestamp in descending order by first displaying the 0 timestamp −
mysql> select *from DemoTable order by (`timestamp`=0) DESC,`timestamp` DESC;
This will produce the following output −
+---------------------+ | timestamp | +---------------------+ | 0000-00-00 00:00:00 | | 2019-12-31 10:50:45 | | 2019-08-17 06:17:12 | | 2018-01-10 12:34:45 | +---------------------+ 4 rows in set (0.00 sec)
Advertisements