Question

Is there any thing from which we can faster get the no. of rows in a table instead of using count(1). Further there are two cases :

a) when we want to get the no. of rows in a table.

b) when we just want to know if there is at-least one row.

Thanks in advance.

Was it helpful?

Solution

a) You can get table row counts from system tables, 1 example is as per Uri Dimant's blog post here.

b) I'd always use EXISTS:

IF EXISTS(SELECT * FROM YourTable)

OTHER TIPS

b) when we just want tot know if there is atleast one row.

SELECT TOP 1 myField FROM myTable [WHERE .....]

To know the count of all rows in the table without scanning them you can use

select SUM(row_count) AS row_count
from sys.dm_db_partition_stats
where object_id = object_id('dbo.tblName')
    and index_id < 2

I'm not sure if there are any caveats with that approach. (Presumably it might either include the count for non committed records or not include changes made within your current transaction)

b) Linq-to-Sql generates

EXISTS (SELECT NULL FROM Table....)

a) No.

b) You can use the exists function, which only checks if there is a result and doesn't actually get the result.

There is this approach, using sysobjects and sysindexes:

Counting rows for all tables at once

It's worked well for me in the past.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top