Atlanta Custom Software Development 

 
   Search        Code/Page
 

User Login
Email

Password

 

Forgot the Password?
Services
» Web Development
» Maintenance
» Data Integration/BI
» Information Management
Programming
  Database
Automation
OS/Networking
Graphics
Links
Tools
» Regular Expr Tester
» Free Tools


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

Click here to copy the following block
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 for SQL Server 6.5 or SET SHOWPLAN_TEXT ON for SQL Server 7.0/2000. 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:

Click here to copy the following block
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:

Click here to copy the following block
SELECT rows FROM sysindexes WHERE id = OBJECT_ID('table_name') AND indid < 2

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.

This is the example:

Click here to copy the following block
SET STATISTICS IO ON
GO
SELECT count(*) FROM tbTest
GO
SELECT rows FROM sysindexes WHERE id = OBJECT_ID('tbTest') AND indid < 2
GO
SET STATISTICS IO OFF
GO

This is the result:

----------- 
10000

(1 row(s) affected)

Table 'tbTest'. Scan count 1, logical reads 32, physical reads 0, read-ahead reads 0.
rows        
----------- 
10000

(1 row(s) affected)

Table 'sysindexes'. Scan count 1, logical reads 2, physical reads 0, read-ahead reads 0.

So, you can improve the speed of the first query in several times. This works for SQL Server 6.5 and SQL Server 7.0/2000 as well.


Submitted By : Nayan Patel  (Member Since : 5/26/2004 12:23:06 PM)

Job Description : He is the moderator of this site and currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting.
View all (893) submissions by this author  (Birth Date : 7/14/1981 )


Home   |  Comment   |  Contact Us   |  Privacy Policy   |  Terms & Conditions   |  BlogsZappySys

© 2008 BinaryWorld LLC. All rights reserved.