Here I have some records, I want to search for records from 8:30 AM to 9:30 AM.
I tried these query but not working:
select * from table_name where '8:30 AM' BETWEEN start_time and end_time OR '9:30 AM' BETWEEN start_time and end_time
select *
from time_test
where STR_TO_DATE(start_time, '%h:%i %p') BETWEEN STR_TO_DATE('08:30 AM', '%h:%i %p') AND STR_TO_DATE('09:30 AM', '%h:%i %p')
OR STR_TO_DATE(end_time, '%h:%i %p') BETWEEN STR_TO_DATE('08:30 AM', '%h:%i %p') AND STR_TO_DATE('09:30 AM', '%h:%i %p')
Here is table sql :
DROP TABLE IF EXISTS `time_test`;
CREATE TABLE IF NOT EXISTS `time_test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`start_time` varchar(20) NOT NULL,
`end_time` varchar(20) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=9 DEFAULT CHARSET=latin1;
INSERT INTO `time_test` (`id`, `name`, `start_time`, `end_time`) VALUES
(1, 'R1', '8:00 AM', '9:00 AM'),
(2, 'R2', '9:00 AM', '10:00 AM'),
(3, 'R1', '8:00', '9:00'),
(4, 'R2', '9:00', '10:00'),
(5, 'R2', '1:00 PM ', '2:00 PM'),
(6, 'R2', '13:00 ', '14:00'),
(7, 'R1', '8:00 PM', '9:00 PM'),
(8, 'R1', '8:30 AM', '9:30 AM');
3
Answers
You could use the DATE() function. In my example using
DATETIME
. Can try with yourdatabase
records.However, for better performance you could use..
You can check HERE for details or read THIS.
You can convert to minutes and add where conditions:
View example :
since you’re not storing the data as
DATETIME
format, to select a records ranged limited to only within8:30
to9:30
, you could useSTR_TO_DATE
:To also select a records ranged outside the
8:30
and9:30
range :