SQL Server: Retrieving the number of rows in all tables in a database

by Stephen Horsfield 9. January 2008 12:01

Overview

I'm in the process of reviewing a database for performance analysis.  One of the most important tasks to perform is reviewing of statistics.  Because this database is currently live, I cannot get the locks to use the sys.dm_db_index_physical_stats built-in function.  I have an Oracle background and didn't know how to get the row count quickly.  Here's my solution...

References

Solution

I use the following code to get the total number of rows for all tables in the current database:

SELECT sysobjects.[name], max(sysindexes.[rows]) AS TableRows,
  CAST(
    CASE max(sysindexes.[rows])
      WHEN 0 THEN -0 
      ELSE LOG10(max(sysindexes.[rows])) 
    END
    AS NUMERIC(5,2))
  AS L10_TableRows
FROM sysindexes INNER JOIN sysobjects ON sysindexes.[id] = sysobjects.[id]
WHERE sysobjects.xtype = 'U'
GROUP BY sysobjects.[name]
ORDER BY max(rows) DESC
GO

Versions

Metadata

Tags:

IT Management | Software Development | SQL Server

Comments

3/18/2008 10:22:14 AM #

really good ,it helps me alot

ran |

4/26/2008 9:17:36 AM #

very nice work.

Muhammad Azim |

4/28/2008 11:51:29 AM #

Do you know of a similar trick for oracle too by any chance?

Dave |

4/28/2008 11:59:22 AM #

It is quite a long time since I worked with Oracle.  However, the row statistics were available in the management tools. If you need a query-based solution, I'm afraid I can't help.

Sorry.

Stephen Horsfield |

10/17/2008 12:00:24 PM #

Hey Dave! for oracle, why don't you use the following code.
----------
BEGIN
        EXECUTE IMMEDIATE 'DROP TABLE zzz_tblCount PURGE'; EXCEPTION WHEN OTHERS THEN NULL;
END;
/
--------------------------------------------------------------------------------
CREATE TABLE zzz_tblCount
(
  TBLNAME VARCHAR2(30),
  CROWS VARCHAR2(10)
);
-------------------------------------
DECLARE
  CURSOR MON_CURSOR IS  SELECT TNAME TABLENAME  FROM TAB WHERE TNAME NOT LIKE '%BIN%';
BEGIN
        FOR a IN MON_CURSOR LOOP

        BEGIN
        EXECUTE IMMEDIATE
        'INSERT INTO /*+ parallel(A,10) */  zzz_tblCount A
        (
    TBLNAME,
    CROWS
    )
  SELECT
  '''||a.TABLENAME||''',
  count(*)
  
  FROM
        '|| a.TABLENAME||'  a';
  END;
END LOOP;
END;
/
--------
select * from zzz_tblCount;

Mahesh Acharya |

Powered by BlogEngine.NET 1.5.0.7
Theme by Interakting

Interakting

A full service digital agency offering online strategy, design and usability, systems integration and online marketing services that deliver real business benefits and ensure your online objectives are met.

Calendar

<<  February 2012  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
2728291234
567891011

View posts in large calendar