In my program I have to run thousands of COUNT
operations each with different conditions.
E.g.
SELECT COUNT(*) FROM Contacts WHERE X='value1' AND Y='value2';
SELECT COUNT(*) FROM Contacts WHERE Z='value3' AND S='value4' AND H='value5';
The number of these operations equals the number of records in my Contacts table. So as the number of contacts increase I am going to have to run more COUNT
s.
As one might expect, the queries are going to take a long time to complete. So I am looking for a way to make them run faster. I read the answer to this question in which the user recommends running
SELECT
Total_Rows= SUM(st.row_count)
FROM
sys.dm_db_partition_stats st
Instead of normal COUNT
. I am wondering if this is really a time-saver?
The problem I am having with comparing the two operations is that for a specific COUNT
, the execution time becomes less with second and third runs. Apparently SQL server caches some query results. So I am unable to see which one is truly faster. I am putting my queries between
set statistics time on
--query
set statistics time off
to see the exact run time. Is there a way to compare the two or is there a way in general to make the COUNT
s faster?