I wonder if anyone has come across this issue before.
I have a string converted to a date and sorted ascending. The date is sorting numerically but it is not sorting on the month. I wonder if anyone has had this issue and can shed some insight as to how to get the date to sort correctly.
SELECT
u.url_id,
url,
title,
description,
pub_date,
DATE_FORMAT(STR_TO_DATE(pub_date, '%d-%b-%Y'), '%d.%b.%Y') AS pub_date,
pub_date AS sortdate
FROM
urls AS u,
url_associations AS ua
WHERE
u.url_id = ua.url_id
AND ua.url_category_id=$type
AND ua.approved = 'Y'
ORDER BY
sortdate DESC
The above is the code and it works but the date isn’t sorting eg it sorts like this:
29-may-2009
28-may-2009
27-may-2009
02-june-2009
01-june-2009
Okay, I was a bit confused before. Your original query is somewhat confusing as you’re selecting
pub_datein the list of columns, and then a conversion also aspub_date. However, you were then sorting by thepub_datecolumn (effectively, givensortdate as pub_date) – which appears to be a string column.Your ordering should be on the column after conversion to a date, but before conversion to a string:
Note that I’ve renamed the “formatted” version to
formatted_date. It’s not clear whether you still need to select the originalpub_dateor not. It’s possible that theformatted_datebit could be:but I’m not entirely sure. I’d hope that the query optimizer would figure that out anyway.
Does your
pub_datecolumn really have to be a string? Why not keep it as a more appropriate type in the database to start with, to avoid all the parsing?