To display dates like “01 August 2019”, use ORDER BY STR_TO_DATE(). Let us first create a −
mysql> create table DemoTable1435 -> ( -> DueDate varchar(60) -> ); Query OK, 0 rows affected (1.08 sec)
Insert some records in the table using insert −
mysql> insert into DemoTable1435 values('01 August 2019'); Query OK, 1 row affected (0.34 sec) mysql> insert into DemoTable1435 values('01 Feb 2018'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable1435 values('31 Jan 2017'); Query OK, 1 row affected (0.08 sec) mysql> insert into DemoTable1435 values('01 March 2019'); Query OK, 1 row affected (0.11 sec)
Display all records from the table using select −
mysql> select * from DemoTable1435;
This will produce the following output −
+----------------+ | DueDate | +----------------+ | 01 August 2019 | | 01 Feb 2018 | | 31 Jan 2017 | | 01 March 2019 | +----------------+ 4 rows in set (0.00 sec)
Following is the query to order dates in MySQL with the format “01 August 2019” −
mysql> select * from DemoTable1435 -> order by str_to_date(DueDate,'%d %M %Y');
This will produce the following output −
+----------------+ | DueDate | +----------------+ | 31 Jan 2017 | | 01 Feb 2018 | | 01 March 2019 | | 01 August 2019 | +----------------+ 4 rows in set (0.04 sec)