简体   繁体   中英

MYSQL ORDER BY date of type Varchar

I want to sort my resultset with respect to date which is of varchar type and in this format (dd/MMM/YYYY) but the problem is its not working fine. I am using this query after a lot of search but still unable to get my desired result.

SELECT `batch_expiry` FROM `batchwise_stock` ORDER BY str_to_date(`batch_expiry`, '%d/%m/%Y')

Sorting is Not doing properly but getting this sorted dates

29/Apr/2020
03/May/2020
16/May/2020
12/May/2020
14/May/2020

Please need help, Thanks in advance.

The issue is that your dates are not in the format %Y/%m/%d . In that format, the month is numeric . Your format is %Y/%b/%d , so use that:

order by str_to_date(batch_expiry, '%d/%b/%Y')

Here is a db<>fiddle.

The result of your expression is NULL , because the date column cannot be converted into that format. All the order by keys are then equivalent, so the ordering in the result set is arbitrary.

As Strawberry points out in a comment, you should store your date values using the proper type, not as a string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM