i would like to select * from table where dates between (some_date and another_date)
the problem is that the dates are stored as varchar
!
IF you are using SQl use this query
Data
DECLARE @Dates TABLE (StartDate varchar(100));
INSERT INTO @Dates VALUES ('7/1/2010 9:10 AM');
INSERT INTO @Dates VALUES ('7/5/2010 10:33 AM');
INSERT INTO @Dates VALUES ('7/13/2010 04:53 AM');
INSERT INTO @Dates VALUES ('7/22/2010 8:45 AM');
INSERT INTO @Dates VALUES ('7/10/2010 11:20 AM');
INSERT INTO @Dates VALUES ('7/11/2010 12:40 AM');
Query:
SELECT * FROM @Dates
WHERE (CONVERT(datetime,StartDate,101) >= CONVERT(datetime,'7/1/2010 9:10 AM',101))
AND (CONVERT(datetime,StartDate,101) <= CONVERT(datetime,'7/15/2010 9:10 AM',101))
ORDER BY CONVERT(datetime,StartDate,101)
You can CAST
your varchar values to DATETIME or DATE type.
WHERE CAST(dates AS DATE) BETWEEN (7/28/10 and 7/29/10)
This might not be an optimal solution, because you may lose the benefit that indexes provide.
Use STR_TO_DATE to convert the strings to the DateTime data type. The format shorthand is found under DATE_FORMAT:
STR_TO_DATE(column, '%m/%/d/%Y %h:%i:%s %p')
The problem is, you'll have to update the VARCHAR dates to all be the same format first, before you can use:
WHERE STR_TO_DATE(reporttime, '%m/%/d/%Y %h:%i:%s %p') BETWEEN STR_TO_DATE(some_date, '%m/%/d/%Y')
AND STR_TO_DATE(another_date, '%m/%/d/%Y')
Date formats are not consistent (some use hyphens, others slashes and Year/Month/day order can be totally different...), so STR_TO_DATE is the most accommodating & consistent means of turning a string into a DateTime. Only after the value is DateTime, does Date/Time functionality become available like DATE() to get only the date portion...
Because of the data type change, an index on some_date & another_date columns can not be used.
This Date query will work perfectly...
Database 'Date' Will be like '01/01/2016' and datatype is 'varchar'
SELECT * FROM `test` WHERE STR_TO_DATE(`test`.`date`, '%d/%m/%Y') BETWEEN '2016-01-01' AND '2016-01-31' ORDER BY `test`.`date` ASC
If date is in Varchar
Query AND c.sentdate > '2016-jun-15'
You want to search between dates, store them as dates. By storing them as strings you're shooting yourself in the foot.
You'd basically need to extract date part from the string (using SUBSTR()
or LEFT()
) and parse it to date format (using STR_TO_DATE()
).
The performance of such solution will be appaling.
STR_TO_DATE(LEFT(reporttime,LOCATE(' ',reporttime)),'%m/%d/%Y') BETWEEN '2010-07-28' AND '2010-07-29'