58

How to select data from mysql table past date to current date? For example, Select data from 1 january 2009 until current date ??

My column "datetime" is in datetime date type. Please help, thanks

Edit:

If let say i want to get day per day data from 1 january 2009, how to write the query? Use count and between function?

4 Answers 4

94
select * from *table_name* where *datetime_column* between '01/01/2009' and curdate()

or using >= and <= :

select * from *table_name* where *datetime_column* >= '01/01/2009' and *datetime_column* <= curdate()
Sign up to request clarification or add additional context in comments.

10 Comments

Cool. It works. LAST question: If I want to show data per day since 01/01/2009, must use count function right? Any idea how to implement?
You can use "group by" and "order by", like this: select * from [table_name] where [datetime_column] between '01/01/2009' and curdate() group by [datetime_column] order by [datetime_column]
i tried this: SELECT , count() from table WHERE datetime BETWEEN '2009-01-01' AND '2009-09-01' GROUP BY datetime; but the count is 1. it supposed to be, 10, 5, 8 etc...
You have to include the column name you want the count of inside count(). So, you would use count(datetime) in this case.
Also, you have to make sure that you are grouping on fields with the same value. If you have want to group all values for a date regardless of time, you will have to use the DATE() function to get the date part of the datetime.
|
26

All the above works, and here is another way if you just want to number of days/time back rather a entering date

select * from *table_name* where *datetime_column* BETWEEN DATE_SUB(NOW(), INTERVAL 30 DAY)  AND NOW() 

Comments

15

You can use now() like:

Select data from tablename where datetime >= "01-01-2009 00:00:00" and datetime <= now();

Comments

4

Late answer, but the accepted answer didn't work for me.
If you set both start and end dates manually (not using curdate()), make sure to specify the hours, minutes and seconds (2019-12-02 23:59:59) on the end date or you won't get any results from that day, i.e.:

This WILL include records from 2019-12-02:

SELECT *SOMEFIELDS* FROM *YOURTABLE* where *YOURDATEFIELD* between '2019-12-01' and '2019-12-02 23:59:59'

This WON'T include records from 2019-12-02:

SELECT *SOMEFIELDS* FROM *YOURTABLE* where *YOURDATEFIELD* between '2019-12-01' and '2019-12-02'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.