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

dba.stackexchange https://dba.stackexchange.com/questions/229794

Question

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;

Was it helpful?

Solution

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.

OTHER TIPS

I have dates in the format of 06-02-2019

Unwritten Rule of Databases - Dates have no format.

Not any that you or I need to worry about, anyway.

BTW; When is "06-02-2019"? June 2nd or the 6th of February?

The ordering rules for Strings and Dates are [very] different.

As we all know 
   31/12/2018 < 01/01/2019
but 
   "31/12/2018" > "01/01/2019"   (because "3" > "0")

If you want to do "date" things with a field then it really, really ought to be a Date field. Trying to do anything else is just asking for trouble. Trying to do any sort of conversion "on the fly" is problematic ("dodgy" data loses data or breaks the query completely) and will be slow, having to run the conversion function on each and every row in the table (i.e. table-scanning!).

Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top