MySQL ORDER BY Date field not in date format?


The following is the syntax to order by date field which is not in date format

select *from yourTableName
order by
STR_TO_DATE(yourColumnName,'%d/%m/%Y') DESC;

To understand the above syntax, let us create a table. The query to create a table is as follows

mysql> create table orderByDateFormatDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> ArrivalDatetime varchar(100)
   -> );
Query OK, 0 rows affected (0.73 sec)

Insert some records in the table using insert command. The query is as follows −

mysql> insert into orderByDateFormatDemo(ArrivalDatetime) values('01/10/2012');
Query OK, 1 row affected (0.20 sec)
mysql> insert into orderByDateFormatDemo(ArrivalDatetime) values('03/11/2010');
Query OK, 1 row affected (0.15 sec)
mysql> insert into orderByDateFormatDemo(ArrivalDatetime) values('04/09/2018');
Query OK, 1 row affected (0.14 sec)
mysql> insert into orderByDateFormatDemo(ArrivalDatetime) values('31/01/2019');
Query OK, 1 row affected (0.17 sec)
mysql> insert into orderByDateFormatDemo(ArrivalDatetime) values('21/04/2017');
Query OK, 1 row affected (0.21 sec)
mysql> insert into orderByDateFormatDemo(ArrivalDatetime) values('23/05/2016');
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement. The query is as follows −

mysql> select *from orderByDateFormatDemo;

The following is the output

+----+-----------------+
| Id | ArrivalDatetime |
+----+-----------------+
|  1 | 01/10/2012      |
|  2 | 03/11/2010      |
|  3 | 04/09/2018      |
|  4 | 31/01/2019      |
|  5 | 21/04/2017      |
|  6 | 23/05/2016      |
+----+-----------------+
6 rows in set (0.00 sec)

Here is the query to ORDER BY date field which is not in date format

mysql> select *from orderByDateFormatDemo
   -> order by
   -> STR_TO_DATE(ArrivalDatetime,'%d/%m/%Y') DESC;

The following is the output

+----+-----------------+
| Id | ArrivalDatetime |
+----+-----------------+
|  4 | 31/01/2019      |
|  3 | 04/09/2018      |
|  5 | 21/04/2017      |
|  6 | 23/05/2016      |
|  1 | 01/10/2012      |
|  2 | 03/11/2010      |
+----+-----------------+
6 rows in set (0.04 sec)

Updated on: 30-Jul-2019

564 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements