views:

94

answers:

6

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.

+2  A: 

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

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

shahkalpesh
A: 

There is this approach, using sysobjects and sysindexes:

http://stackoverflow.com/questions/428458/counting-rows-for-all-tables-at-once

It's worked well for me in the past.

jamauss
+1  A: 

b) Linq-to-Sql generates

EXISTS (SELECT NULL FROM Table....)
ck
+2  A: 

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)
AdaTheDev
+1  A: 

a) No.

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

Guffa
+2  A: 

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)

Martin Smith
Isn't that what `SELECT COUNT(*)` actually does, and without your caveats?
egrunin
@egrunin: No. [Execution Plans...](http://img180.imageshack.us/img180/3977/executionplan.jpg)
Martin Smith
@Martin Smith: thanks for the pics.
egrunin
Is it advisable to use this ? further is this what you are using as a pro ?
HotTester