Pages

Friday, March 11, 2011

Number of rows inserted by hour

Almost all the time, when your database is large enough, you will be curious to know how busy the database is, and one of the ways is to find it is to look at the number of inserted row per hour.
The idea is pretty simple: Select records by date, group by the hour and count. It does get interesting when we start thinking about var types we are using and io statistics.
Here's the first query I wrote just to get the job done:

select datepart(hh,createDate) [hour],
count(datepart(hh,createdate)) RecordCount 
from myBusyTable
where CONVERT(VARCHAR(10),createDate, 101) = '01/01/2011'
group by datepart(hh,createDate))

where createDate is a datetime when the record was first inserted in the database. Note that I am using varchar to compare my date.

It took me 2 secs to run it. Set the IO STATISTICS ON and the logical reads was 9520. Changed the query to get data for seven days, and it took 40 secs.
Of course,  better way to do it would be to use datetime variables:

declare @startDate datetime
declare @endDate datetime
set @startDate = '01/01/2011'
set @endDate = @startDate + 1 -- goes until midnight next day
select datepart(hh,createDate) [hour],
count(datepart(hh,createdate)) RecordCount 
from myBusyTable
where createDate between @startDate and @endDate
group by datepart(hh,createDate)

This one completed is ms. And the logical reads reduced to 67 (from 9520).
And, if I need to run it for multiple days, I simply group it by date, and hour like below:

declare @startDate datetime
declare @endDate datetime
set @startDate = '01/01/2011'
set @endDate = @startDate + 7 -- goes until midnight next day
select convert(varchar(10),createDate, 101) date,
datepart(hh,createDate) [hour],
count(datepart(hh,createdate)) RecordCount 
from myBusyTable
where createDate between @startDate and @endDate
group by convert(varchar(10),createDate, 101), datepart(hh,createDate)
order by convert(varchar(10),createDate, 101), datepart(hh,createDate)


Here's the output:


No comments:

Post a Comment