Is it possible I make a simple query to count how many records I have in a determined period of time like a Year, month or day, having a TIMESTAMP
field, like:
SELECT COUNT(id)
FROM stats
WHERE record_date.YEAR = 2009
GROUP BY record_date.YEAR
Or even:
SELECT COUNT(id)
FROM stats
GROUP BY record_date.YEAR, record_date.MONTH
To have a monthly statistic.
Thanks!
If you want to filter records for a particular year (e.g. 2000) then optimize the
WHERE
clause like this:Instead of:
The results were generated against a table containing 300k rows and index on date column.
As for the
GROUP BY
clause, I tested the three variants against the above mentioned table; here are the results:The last one is the winner.
You can do this simply Mysql DATE_FORMAT() function in GROUP BY. You may want to add an extra column for added clarity in some cases such as where records span several years then same month occurs in different years.Here so many option you can customize this. Please read this befor starting. Hope it should be very helpful for you. Here is sample query for your understanding
If you want to group by date in MySQL then use the code below:
Hope this saves some time for the ones who are going to find this thread.
I prefer to optimize the one year group selection like so:
This way you can just bind the year in once, e.g.
'2009'
, with a named parameter and don't need to worry about adding'-01-01'
or passing in'2010'
separately.Also, as presumably we are just counting rows and
id
is neverNULL
, I preferCOUNT(*)
toCOUNT(id)
.The following query worked for me in Oracle Database 12c Release 12.1.0.1.0
Check out the date and time functions in MySQL.