Home » Php » php – MySQL ORDER BY Date field which is not in date format

php – MySQL ORDER BY Date field which is not in date format

Posted by: admin July 12, 2020 Leave a comment


I have a field containing dates in this format DD/MM/YYYY and I need to order the results DESC by this field, but it is saved as a VARCHAR and I cannot change this. Is there a workaround?

There really is no way for me to change the field type so please don’t say this is a bad way to do this as I already know. I just need to know if it is possible.

Thanks for any help and advice in advance.

How to&Answers:

You can do it by the following way,

FROM ...
ORDER BY STR_TO_DATE(yourDate,'%d-%m-%Y') DESC




order by str_to_date(myCol, '%d/%m/%Y')


use this


   SELECT * FROM table_name ORDER BY  STR_TO_DATE(date_field, '%d-%M-%Y') DESC


ORDER BY CONCAT(SUBSTR(field, 7, 4), SUBSTR(field, 4, 2), SUBSTR(field, 1, 2)) DESC


Use STR_TO_DATE() MySQL function:

SELECT * FROM your_table ORDER BY STR_TO_DATE(your_date_column, '%d/%M/%Y') DESC;

sidenote: STR_TO_DATE converts String to Date while DATE_FORMAT converts Date to String


It depends on how you stored date in your date field. In my case, it is separated by "/" so I used –

ORDER BY STR_TO_DATE(report_date, '%m/%d/%Y') DESC;

In case, if you’re using "-" to separate date, month and year, then you can use –

ORDER BY STR_TO_DATE(report_date, '%m-%d-%Y') DESC;

enter image description here