In the SQL statement below the results are returned out of order. If they were in ascending or descending order it would make sense, but it seems there is no order here.
Any insights as to why the ORDER BY function isn’t sorting by the ‘date’ alias would be very much appreciated.
SQL Statement:
SELECT id, date, type
FROM (SELECT resume_id AS id, DATE_FORMAT( date_mod, '%M %e, %Y' ) AS date, 'resume' AS TYPE
FROM resumes
WHERE user_id = '$user_id'
UNION ALL
SELECT profile_id, DATE_FORMAT( date_mod, '%M %e, %Y' ) AS date, 'profile'
FROM profiles
WHERE user_id = '$user_id'
ORDER BY date DESC LIMIT 5) AS d1
ORDER BY date
Results:
Resume was updated on February 14, 2012
Resume was updated on February 15, 2012
Resume was updated on February 15, 2012
Resume was updated on February 9, 2012
Profile was updated on February 9, 2012
It’s sorting them as strings because you’ve converted the dates to strings using
DATE_FORMAT(note that as a string “February 15…” is lower than “February 9…” because 1 comes before 9 in the “alphabet”). The solution is to sort by the real date indate_mod. You could do it directly by just adding indate_modto the selects and changing the order, like this:But even better would be to simplify it by selecting only
date_modin the sub-query (i.e. no formatted version) and doing theDATE_FORMATlast in the outer query: