MySQL ORDER BY Date field which is not in date format
Asked Answered
T

6

8

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.

Thaxton answered 5/6, 2013 at 9:24 Comment(1)
https://mcmap.net/q/321749/-parse-date-in-mysqlAmphibrach
C
25

You can do it by the following way,

SELECT ...
FROM ...
ORDER BY STR_TO_DATE(yourDate,'%d-%m-%Y') DESC
Courtship answered 5/6, 2013 at 9:26 Comment(0)
G
4

Using STR_TO_DATE:

http://dev.mysql.com/doc/refman/5.6/en/date-and-time-functions.html#function_str-to-date

...
order by str_to_date(myCol, '%d/%m/%Y')
Gulf answered 5/6, 2013 at 9:26 Comment(1)
Exactly same as @PSR :)Roeser
L
1

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

Lifeordeath answered 5/6, 2013 at 9:28 Comment(0)
D
1

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

Decoy answered 21/6, 2020 at 9:4 Comment(0)
A
0

use this

STR_TO_DATE

   SELECT * FROM table_name ORDER BY  STR_TO_DATE(date_field, '%d-%M-%Y') DESC
Araarab answered 5/6, 2013 at 9:26 Comment(0)
A
0
ORDER BY CONCAT(SUBSTR(field, 7, 4), SUBSTR(field, 4, 2), SUBSTR(field, 1, 2)) DESC
Alvey answered 5/6, 2013 at 9:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.