Order By date ASC in MySQL?


You can use STR_TO_DATE() function. Let us first create a table −

mysql> create table DemoTable
   (
   AdmissionDate varchar(200)
   );
Query OK, 0 rows affected (1.19 sec)

Insert records in the table using insert command −

mysql> insert into DemoTable values('12-01-2019');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('14-12-2016');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('26-04-2018');
Query OK, 1 row affected (0.34 sec)
mysql> insert into DemoTable values('31-05-2013');
Query OK, 1 row affected (0.30 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable;

This will produce the following output −

+---------------+
| AdmissionDate |
+---------------+
| 12-01-2019    |
| 14-12-2016    |
| 26-04-2018    |
| 31-05-2013    |
+---------------+
4 rows in set (0.00 sec)

Following is the query to sort order by date ASC −

mysql> select *from DemoTable ORDER BY STR_TO_DATE(AdmissionDate,'%d-%m-%Y') ASC;

This will produce the following output −

+---------------+
| AdmissionDate |
+---------------+
| 31-05-2013    |
| 14-12-2016    |
| 26-04-2018    |
| 12-01-2019    |
+---------------+
4 rows in set (0.00 sec)

Updated on: 30-Jul-2019

245 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements