Order By date ASC in MySQL?

MySQLMySQLi Database

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)
raja
Published on 03-May-2019 14:16:42
Advertisements