Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / database / SQL-Server

A better way to count(*)

4.00/5 (2 votes)
7 Jun 2010CPOL 9.9K  
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)