4

DBAs have told me that when using T-SQL:

select count(id) from tableName

is faster than

select count(*) from tablenName

if id is the primary key.

Extrapolating that to LINQ-TO-SQL is the following accurate?

This LINQ-to-SQL statement:

int count = dataContext.TableName.Select(primaryKeyId => primaryKeyId).Count();

is more performant than this one:

int count = dataContext.TableName.Count();
3
  • 5
    What DBAs have told you that? They are usually interpreted the same by the optimizer.
    – user610217
    Commented Apr 20, 2012 at 15:56
  • 1
    On most RDBMS, that is not going to make any difference whatsoever... and if it did (which it usually won't), count(1) would be, potentially, even better. However, re your final "is more performant" question - have you tried it? in particular, trap the SQL used for both queries, see if that is different. If it is different, run it both ways with stats-io enabled, etc. Commented Apr 20, 2012 at 15:58
  • @JeremyHolovacs would you like his SSN? :) - Seriously: it was someone who I worked with and took it on face value and never questioned it. From the comments and accepted answer it looks like what I was told is false. Thanks to everyone for clearing this up!
    – Guy
    Commented Apr 20, 2012 at 16:23

2 Answers 2

6

As I understand it there's no difference between your two select count statements.

Using LINQPad we can examine the T-SQL generated by different LINQ statements.

For Linq to SQL both

TableName.Select(primaryKeyId => primaryKeyId).Count();

and

TableName.Count();

generate the same SQL

SELECT COUNT(*) AS [value] FROM [dbo].[TableName] AS [t0]

For Linq to Entites, again they both generate the same SQL, but now it's

SELECT 
[GroupBy1].[A1] AS [C1]
FROM ( SELECT 
    COUNT(1) AS [A1]
    FROM [dbo].[TableName] AS [Extent1]
)  AS [GroupBy1]
0

I know this is an old one but watch out with sql server! Count does not count null values so the two statements may not be equivalent if your primary key field is nullable. see

create table #a(col int null)

insert into #a values (null)

select COUNT(*) 
from #a;

select COUNT(col)
from #a;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.