Tuesday, May 18, 2010

Alternative way to get the table's row count


To get the total row count in a table, we usually use the following select statement:

SELECT count(*) FROM table_name

This query performs full table scan to get the row count. You can check it by setting SET SHOWPLAN ON , SET SHOWPLAN_TEXT ON for SQL Server . So, if the table is very big, it can take a lot of time. In this example, the tbTest table will be created and 10000 rows will be inserted into this table

CREATE TABLE tbTest (
id int identity primary key,
Name char(10)
)
GO
DECLARE @i int
SELECT @i = 1
WHILE @i <= 10000 BEGIN INSERT INTO tbTest VALUES (LTRIM(str(@i))) SELECT @i = @i + 1 END GO
There is another way to determine the total row count in a table. You can use the sysindexes system table for this purpose. There is ROWS column in the sysindexes table. This column contains the total row count for each table in your database. So, you can use the following select statement instead of above one:

SELECT rows FROM sysindexes
WHERE id = OBJECT_ID('table_name') AND indid <>

There are physical read and logical read operations. A logical read occurs if the page is currently in the cache. If the page is not currently in the cache, a physical read is performed to read the page into the cache. To see how many logical or physical read operations were made, you can use SET STATISTICS IO ON command.


SET STATISTICS IO ON
GO
SELECT count(1) FROM tbTest
GO
SELECT rows FROM sys.sysindexes WHERE id = OBJECT_ID('tbTest') AND indid < 2 GO SET STATISTICS IO OFF GO




No comments:

Post a Comment