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.
You can do it by the following way,
SELECT ... FROM ... ORDER BY STR_TO_DATE(yourDate,'%d-%m-%Y') DESC
... order by str_to_date(myCol, '%d/%m/%Y')
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
STR_TO_DATE() MySQL function:
SELECT * FROM your_table ORDER BY STR_TO_DATE(your_date_column, '%d/%M/%Y') DESC;
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;