45

I am stuck with a problem in MySQL. I want to get the count of records between two date-time entries.
For example:
I have a column in my table named 'created' having the datetime data type.

I want to count records which were created date-time between "TODAY'S 4:30 AM" and "CURRENT DATE TIME".

I tried some of MySQL's functions but still no luck with it.

Can you please help me with this? thanks.

gautamlakum
  • 11,815
  • 23
  • 67
  • 90

4 Answers4

96

May be with:

SELECT count(*) FROM `table` 
where 
    created_at>='2011-03-17 06:42:10' and created_at<='2011-03-17 07:42:50';

or use between:

SELECT count(*) FROM `table` 
where 
    created_at between '2011-03-17 06:42:10' and '2011-03-17 07:42:50';

You can change the datetime as per your need. May be use curdate() or now() to get the desired dates.

Harry Joy
  • 58,650
  • 30
  • 162
  • 207
  • 14
    Please note that order matters, you need to first write smaller date time and then bigger date time – Hafiz Jun 27 '12 at 10:51
  • What if date and time on separate column. – Satanand Tiwari Oct 28 '17 at 08:46
  • In that case, you will need to a combination of date and time conditions. For example, if you want to filter for some time in a single day then date column will have an equal condition along with time having between condition. In other cases, you can just filter with between in date and order by time get all records of in those dates. – Harry Joy Oct 30 '17 at 07:05
  • 1
    What happens if we don't specify the time in the query, like: **SELECT count(*) FROM `table` where created_at between '2011-03-10' and '2011-03-17';** ? Does MySQL automatically consider the time as: **00:00:00** ? – shasi kanth Apr 19 '18 at 13:15
6
select * from yourtable where created < now() and created > '2011-04-25 04:00:00'
Wes
  • 6,455
  • 3
  • 22
  • 26
5
select * from yourtable 
   where created < now() 
     and created > concat(curdate(),' 4:30:00 AM') 
Shakti Singh
  • 84,385
  • 21
  • 134
  • 153
1

for speed you can do this

WHERE date(created_at) ='2019-10-21'
Aditya Tomar
  • 841
  • 1
  • 13
  • 20