Mysql – How to cast (a) a date value recorded as a VARCHAR to (b) a specific DATE format for (c) use in an ORDER BY clause

castdate formatMySQLorder-by

How would I cast a column value (a "non-MySQL" DATE string retained as a VARCHAR) to a "MySQL date" so it can be used for sorting?

I have dates in the format of 06-02-2019 (6 feb) but MySQL itself doesn't seem to recognize this by just using the default DATE() function.

What I currently have is: SELECT * FROM Services ORDER BY Date(nextdate) DESC;

Best Answer

You are looking for the STR_TO_DATE() function. MySQL expects by default dates in ISO format.

In your particular case it would be something like:

SELECT * FROM Services ORDER BY STR_TO_DATE(nextdate, %d-%m-%Y) DESC;

%d-%m-%Y or %m-%d-%Y, whatever is the "wrong" format you are using.

Using ISO dates (either strings or, preferably, timestamps) plus an index will have the efect that it will speed up your queries.