Reputation: 1307
Hi I have following values stored in MySQL table:
--- ------------------------ -------------------
Id | StartDate (VARCHAR (20)) | EndDate(VARCHAR(20))
--- ------------------------ -------------------
1 | 03-04-2017 | 18-04-2017
I am using the following SQL to find if the date is within the StartDate and EndDate:
SELECT
(date_format(str_to_date('03-04-2017','%d-%m-%Y'),'%d-%m-%Y') >= StartDate
AND
date_format(str_to_date('03-04-2017','%d-%m-%Y'),'%d-%m-%Y') <= EndDate) AS
valid
FROM holiday
My issue is it that when I execute the query and provide 03-04-2017 it returns 1 but also returns 1 when I provide 03-05-2017.
Could someone please highlight what is wrong in this query?
Upvotes: 0
Views: 55
Reputation: 16923
All other answers are good for your question but in my opinion you should convert your database.
It's only sane option.
Using dates in weird VARCHAR
format will have big impact in future. Not only it impacts perfomances of your tables right now but you are missing whole MySQL date API ecosystem because of it.
tmp_start_time DATE
UPDATE holiday SET tmp_start_time = str_to_date(start_time,'%d-%m-%Y')
DATE
UPDATE holiday SET start_time = tmp_start_time
From now on you would be able to use BETWEEN
as everyone else without str_to_date
I just found your comment
unfortunately I cannot change schema
ask yourself twice: are you sure?
Upvotes: 1
Reputation: 15057
Use a query like this:
SELECT *
FROM holiday
WHERE
STR_TO_DATE(StartDate,'%d-%m-%Y')
BETWEEN
str_to_date('03-04-2017','%d-%m-%Y')
AND
str_to_date('03-04-2017','%d-%m-%Y');
sample
mysql> SELECT IF(STR_TO_DATE('11-04-2017','%d-%m-%Y')
-> BETWEEN
-> str_to_date('03-04-2017','%d-%m-%Y')
-> AND
-> str_to_date('10-04-2017','%d-%m-%Y')
->
-> ,'YES','NO') AS ANSWER;
+--------+
| ANSWER |
+--------+
| NO |
+--------+
1 row in set (0,00 sec)
mysql> SELECT IF(STR_TO_DATE('04-04-2017','%d-%m-%Y')
-> BETWEEN
-> str_to_date('03-04-2017','%d-%m-%Y')
-> AND
-> str_to_date('10-04-2017','%d-%m-%Y')
->
-> ,'YES','NO') AS ANSWER;
+--------+
| ANSWER |
+--------+
| YES |
+--------+
1 row in set (0,01 sec)
mysql>
Upvotes: 2
Reputation: 30809
You can use BETWEEN
operator to compare the dates, e.g.:
SELECT *
FROM `table`
WHERE '2017-04-03' BETWEEN start_date AND end_date;
Update
If the dates are stored as varchar
then you need to convert it to date
before comparing, e.g.:
SELECT *
FROM table
WHERE '2017-04-03' BETWEEN STR_TO_DATE(start_date, '%d-%m-%Y') AND STR_TO_DATE(end_date, '%d-%m-%Y');
Here's the SQL Fiddle.
Upvotes: 1