I have a table where there are only DateTime stored as varchar's in ISO Format. I wanted to know what would be the MySQL query to compare given any random DateTime in iso format with the DateTime(in varchar) stored in the table.
I have a table where there are only DateTime stored as varchar's in ISO Format. I wanted to know what would be the MySQL query to compare given any random DateTime in iso format with the DateTime(in varchar) stored in the table.
SELECT
STR_TO_DATE('2020-01-03 17:35:48', GET_FORMAT(DATETIME,'ISO')) <
STR_TO_DATE('2020-02-01 00:00:00', GET_FORMAT(DATETIME,'ISO'));
GET_FORMAT(DATETIME,'ISO') being similar to: %Y-%m-%d %H:%i:%s, you can also do:
SELECT
STR_TO_DATE('2020-01-03 17:35:48', '%Y-%m-%d %H:%i:%s') <
STR_TO_DATE('2020-02-01 00:00:00', '%Y-%m-%d %H:%i:%s');
Once you have a DateTime, you can compare them using all operators: =, <, <=, >, >=, !=, BETWEEN,...
Note: Avoid to store date/time in a VARCHAR column, because:
STR_TO_DATE(mydate) will have to be performed on every rows of your table and will cause a full table scan. The index will contain mydate, but not the result of STR_TO_DATE(mydate), which means it will not be used.Another alternative is to avoid the transformation into date and benefit from the fact that ISO format can be sorted using ASCII comparison. In your specific case, you could do:
SELECT *
FROM TABLE
WHERE traceTime < '2020-02-21T08:40:07.749060'
But still, would be better if traceTime was of type DATETIME, the query would just be the same.
In mysql You can easly convert a string in a datetime using
str_to_date(your_string, your_format)
str_to_date('31-12-2019', '%d-%m-%Y')
https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_str-to-date
https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_date-format