Click here to Skip to main content
15,879,326 members
Articles / Database Development / SQL Server
Tip/Trick

A better way to count(*)

Rate me:
Please Sign up or sign in to vote.
4.00/5 (2 votes)
7 Jun 2010CPOL 9.7K   4  
LINQ translates .count() to a SQL query that uses COUNT(*), but on large tables even count(*) can be too slow. Here's another way
We all know
SQL
SELECT COUNT(*) AS recCount FROM [myTable];

as a means of getting the number of records in [myTable]. But for very large tables this method can be just too slow, even tripping over default timeouts.

Do a quick search on this problem and you can find an alternative for SQL Server which is substantially faster. It looks a little like this.
SQL
USE [myDatabase];
SELECT ISNULL(st.row_count, 0)
FROM [sys].[dm_db_partition_stats] st
WHERE index_id < 2 AND OBJECT_NAME(OBJECT_ID) = 'myTable';


Unfortunately if you use .count() in your LINQ statements you'll also get COUNT(*) in the resulting SQL.

So rather than doing that in your code try the following:
C#
string sqlCount = "SELECT ISNULL(st.row_count, 0)
FROM [sys].[dm_db_partition_stats] st
WHERE index_id < 2 AND OBJECT_NAME(OBJECT_ID) = '||TableName||';";
long myRecCount = dc.ExecuteQuery<long>(sqlCount.Replace("||TableName||", "myTable")).First();

In the above code dc is the datacontext that you've already instantiated.
Substitute the name of the table you need to get the record count for and you'll get the result in lightening quick time.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Founder md8n
Timor-Leste Timor-Leste
If it ain't broke - that can be arranged.

Comments and Discussions

 
-- There are no messages in this forum --