Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

number of rows SQL Server

How to count or know the number of rows a table has without scaning all the table, maybe using ROW_NUMBER?

like image 842
edgarmtze Avatar asked Mar 04 '11 21:03

edgarmtze


People also ask

How do I find the number of rows in SQL Server?

Use the COUNT aggregate function to count the number of rows in a table. This function takes the name of the column as its argument (e.g., id ) and returns the number of rows for this particular column in the table (e.g., 5).

How do I find the number of rows in a resultset in SQL Server?

To number rows in a result set, you have to use an SQL window function called ROW_NUMBER() . This function assigns a sequential integer number to each result row. However, it can also be used to number records in different ways, such as by subsets.


4 Answers

There is no ROW_NUMBER in SQL Server, just Oracle. Use:

SELECT COUNT(primary_key) FROM table

Where primary key the primary key column of your table.

Since its a primary key, its is already indexed, so SQL can count it without scanning the whole table (it uses a clustered index to be precise, which is much faster than a full table scan)

You could also use sys.indexes schema, but its not accurate, and you would need database admin priviledges to access, and your application database user is not supposed to have grants in that schema

like image 150
MestreLion Avatar answered Oct 04 '22 21:10

MestreLion


If you need a exact count, you will need to do a COUNT(*) which will scan the clustered index.

You can get a rough count using the sys.partitions schema, as shown here http://www.kodyaz.com/articles/sql-rowcount-using-sql-server-system-view-sys-partitions.aspx

Update: To get the count into a variable:

DECLARE @cnt INT;
SELECT @cnt = SUM(rows)
FROM sys.partitions
WHERE
  index_id IN (0, 1)
  AND object_id = OBJECT_ID('MyDB.dbo.MyTable');
SELECT @cnt;
like image 40
The Scrum Meister Avatar answered Oct 04 '22 20:10

The Scrum Meister


SELECT COUNT(*) FROM Table

will return the number of rows

like image 25
Simon Avatar answered Oct 04 '22 20:10

Simon


A little late to the party here, but in SQL Server 2005 on, you could also use the sp_spaceused stored procedure:

DECLARE @rowCount AS INT
DECLARE @spaceUsed TABLE(
    [Name] varchar(64), 
    [Rows] INT,
    [Reserved] VARCHAR(50),
    [Data] VARCHAR(50),
    [Index_Size] VARCHAR(50),
    [Unused] VARCHAR(50)
)
INSERT INTO @spaceUsed EXEC sp_spaceused 'MyTableName'
SET @rowCount = (SELECT TOP 1 [Rows] FROM @spaceUsed)
SELECT @rowCount AS 'Row Count'

I've gotten into the habit of using sp_spaceused in place of SELECT COUNT(*) FROM Table because it is much faster. It will most likely not be as accurate as COUNT(*), however.

MSDN: http://msdn.microsoft.com/en-us/library/ms188776.aspx

like image 24
rsbarro Avatar answered Oct 04 '22 21:10

rsbarro