I have stored dates (dd/mm/yyyy) in text format in a table
in a field called dates
. I want to compare those dates with the current date and if the dates are smaller (if the dates have passed) to move the entire row into a new table called archive
. Tried something with the DATEDIFF()
but I'm new to MySQL and can't figure it out.
1 Answers
I'm going to preface my answer with a short remark: storing "date" values in SQL database in VARCHAR columns is an anti-pattern. MySQL provides native datatype DATE
which is designed to handle "date" values. But that's just a remark, doesn't answer your question.
You can use the convenient MySQL STR_TO_DATE
function to convert strings into DATE
values. For example:
STR_TO_DATE('15/05/2015','%d/%m/%Y')
You could use a column reference in place of the literal, e.g.
STR_TO_DATE(t.mycharcol,'%d/%m/%Y')
and that will return a DATE
value you can compare to another DATE
value, using the standard inequality operator <
for example.
To return the current date from the database, you can use an expression such as
DATE(NOW())
Putting that together, you could write a query like this:
SELECT t.*
FROM t
WHERE STR_TO_DATE(t.mycharcol,'%d/%m/%Y') < DATE(NOW())
If you want to take the result from a SELECT statement and insert those rows into another table, you can use the INSERT ... SELECT
form of the INSERT
statement.
Reference: https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_str-to-date
Beware of the behavior with badly formatted or invalid dates, e.g.
SELECT STR_TO_DATE('35/05/2015','%d/%m/%Y')
, STR_TO_DATE('15-05-2015','%d/%m/%Y')