About Me

My photo
Kozyatağı, İstanbul, Türkiye

Sunday, September 22, 2013

Counting Records Effectively: Reducing Redundant Counting

Sometimes, we need to query database for retrieving count of records that satistfies some condition.
If the count, which is returned from query, is used for comparing to a constant; there is no need to count all of the records.

Suppose that, you have a table in Sql Server as follows:

CREATE TABLE [Users]
(
   [Id]             [BIGINT],
   [Name]           [VARCHAR](100),
   [RegistrationDate] [DATETIME]
) 


And your application code needs to know if "the Count of users whose registration day is >= 2013-01-01, is more than 100 "

 The first query coming to mind is:

SELECT COUNT(*)
FROM   Users U
WHERE  U.RegistrationDate >= '20130101' 


Suppose, you have millions of users. The query above makes you check all, just for comparing to 100, which is a redundant activity.

Now, I am changing it to:

DECLARE @N INT = 100

SELECT COUNT(*)
FROM   (SELECT TOP(@N + 1) 1 AS CNT
        FROM   Users U
        WHERE  U.RegistrationDate >= '20130101')

X 


Now, Counting terminates at server side as soon as 101 records encountered.

The main idea here is that, if I know that the value is going to be compared to 100, so I do NOT need to count if I reach 101 records. Because all the numbers greater than 101 will not affect the result of comparison.

No comments:

Post a Comment