INF: Fast Query to Return Number of Rows in a Table

Last reviewed: April 25, 1997
Article ID: Q73006

The information in this article applies to:

  - Microsoft SQL Server version 4.2 for OS/2

SUMMARY

The following is the query most often used to return the number of rows in a given table:

   SELECT COUNT(*)
   FROM <table name>

For large tables, this query may take a while to run. There is, however, a faster method of determining the number of rows in a table.

MORE INFORMATION

In some applications, you might want to maintain a constant tally of the number of rows in a table. If you use the query shown above, the query expends considerable overhead counting each row of the table.

The "rows" column in the sysindexes table can also return the current number of rows in any given table. Use the following query to retrieve the row count comparatively quickly, since querying the sysindexes table needs to find only one row:

          SELECT rows
          FROM sysindexes
          WHERE id = object_id ("<table name>")
          AND indid < 2

Notes

  1. The "AND indid < 2" clause is necessary because the sysindexes table contains one row for each clustered index, one row for each nonclustered index, and one row for each table that has no clustered index. The "indid" column may contain one of the following values:

          0  if the object is a table
          1  if the object is a clustered index
          >1 if the object is a nonclustered index
    

    The "rows" column is updated dynamically only if "indid" is 0 or 1. If "indid" is greater than 1, the "rows" column is updated only when the index is created and when UPDATE STATISTICS is run. Therefore, adding the "AND indid < 2" clause ensures that the value returned by the query is the current number of rows when the query is run.

  2. The "rows" column is NOT updated dynamically while rows are being added to the table using BCP (regardless of whether slow or fast BCP is used), but is updated immediately after BCP finishes.


Additional query words:
Keywords : kbprg SSrvProg
Version : 4.2
Platform : OS/2


THE INFORMATION PROVIDED IN THE MICROSOFT KNOWLEDGE BASE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. MICROSOFT DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING THE WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL MICROSOFT CORPORATION OR ITS SUPPLIERS BE LIABLE FOR ANY DAMAGES WHATSOEVER INCLUDING DIRECT, INDIRECT, INCIDENTAL, CONSEQUENTIAL, LOSS OF BUSINESS PROFITS OR SPECIAL DAMAGES, EVEN IF MICROSOFT CORPORATION OR ITS SUPPLIERS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME STATES DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES SO THE FOREGOING LIMITATION MAY NOT APPLY.

Last reviewed: April 25, 1997
© 1998 Microsoft Corporation. All rights reserved. Terms of Use.