I’m hurting for an answer on this one. I’m not great at SQL just yet, but I’m trying to write a select statement that finds dates within a certain range. My problem, I think, is that the date values are strings and it doesn’t compare properly. This is the code I’ve got so far.
SELECT CONCAT (suffix, " ", lname, " ", fname, " ", name) AS "Name",
id AS "Member ID",
CONCAT (address1, " ", address2, " ") AS "Address Line 1",
CONCAT (city, " ", state, " - ", zip) AS "Address Line 2",
CASE
WHEN STR_TO_DATE(regionexpires,'%d.%m.%Y') > 01/01/2023 THEN 'Yes'
ELSE 'No'
END AS "Subscriber?"
FROM roster
LIMIT 100000
I’ve tried casting, converting, and the str_to_date function – /’s, .’s, you name it. All 1090 results are No. These should definitely at least have a couple yeses. This is for MySQL, by the by.
2
Answers
IIRC, date’s get formatted like strings in MySQL. So something like
WHEN STR_TO_DATE(regionexpires,'%d-%m-%Y') > '01-01-2023 THEN 'Yes'
Notice the use of dashes in both the formatting string and the date value itself. Slashes might work, don’t have an instance in front of me that I can tests with though.You should never store date or time information as strings. Ideally you would take the time to correct this so that all your queries will be simpler in future.
However to address the immediate issue please get used to concept of "date literal" which is how we give a SQL query a date. It is a good idea to also use the most common ISO 8601 format for these literals e.g. ‘2023-01-01’
So, you comparison needs a valid "date literal" e.g.
Notice that to convert you strings into date, you should use the format of how those strings have been stored. e.g. if your data looks like this:
Then STR_TO_DATE(regionexpires,’%d.%m.%Y’) results in a date and that date can then be compared to a valid "date literal"
However if your data contains just 2 digit years or delimiters other than periods and/or they are in dmy or mdy sequence then you need a different str_to_date for each format your data holds. Plus strings can be invalid dates or even nothing like a date at all. This is why storing dates as strings is a bad idea.
Further information aimed at changing that string column into a date column:
fiddle