The Fastest Way to Count Rows in SQL Server: I Asked Ten DBAs

How do you count rows in SQL Server? It sounds like a beginner question. I asked ten experienced people and got five different answers, every one delivered with total confidence, and not one of them asked me what the number was for.

A green roadside town sign reading POP. 4,212 at the edge of a two-lane road, with a small wooden board hung underneath reading GIVE OR TAKE

The question is missing a word. The missing word changes the answer.

The Answers I Got

Four said COUNT(*). Two said COUNT(1), and one of those two was firm that it is faster. One said COUNT of the primary key. Two went to sys.partitions. One said sp_spaceused, which was the most practical answer of the lot, and nobody else mentioned it.

Ten people, five answers. Each method has a use. Three count rows through a query. The other two report stored counts. Those are different promises.

COUNT(*) Against COUNT(1)

For the same input rows, COUNT(*) and COUNT(1) return the same count. The constant 1 is never null. Changing the spelling is not a performance trick.

In the recorded test behind this post, the table had 200,000 rows. SET STATISTICS IO ON showed the work SQL Server did.

Both did exactly 324 logical reads, meaning page reads from the data cache, not necessarily 324 different pages or disk reads. They used the same plan and index. Counting the primary key also took 324 reads in that test.

The belief that COUNT(1) is faster has been circulating since before some of the people repeating it were born. Compare the actual plans and reads on your workload instead of choosing by folklore.

I use COUNT(*) because it says what it means. It returns an int, with a maximum of 2,147,483,647. Use COUNT_BIG(*) for larger counts; it returns a bigint.

COUNT of a Column Is a Different Question

A handwritten paper tag hanging on the screen door of a quiet farmhouse porch, reading SORRY WE MISSED YOU

This one is not a style choice, and it catches people.

SELECT COUNT(*) FROM dbo.Orders;
SELECT COUNT(ShipDate) FROM dbo.Orders;

The second counts only rows where ShipDate is not null. The original example returned 200,000 against 159,749. About a fifth of the rows had no recorded ship date. A missing date does not, by itself, prove an order never shipped.

Both queries are correct. Only one of them was asked.

I once sat through a painful hour of a reconciliation meeting caused by exactly this. Two teams, two perfectly correct queries, two different totals, and nobody in the room able to say why.

Counting a primary-key column also counts every input row because the column cannot be null. That constraint is reliable. COUNT(*) simply expresses the intent more directly. These rules are defined in the COUNT documentation.

What COUNT(*) Actually Reads

A long row of rural mailboxes along a gravel road at dawn, with a clipboard of tally marks resting on the nearest one under the words ONE PER HOUSE

To answer exactly, SQL Server has to go and read something. It is smarter about what than people expect.

For a rowstore table, SQL Server can scan a narrow nonclustered index that contains every required row. The optimizer chooses among available plans; a narrow index is an option, not a guarantee.

The reasoning is easy to follow. A narrow index means fewer pages, and fewer pages means less work for the same answer.

That is where the original example’s 324 reads came from. Its clustered index was roughly six thousand pages. The counting plan scanned a small date-column index instead. These are measurements from that setup, not page counts to expect on your table.

The mailbox photo captures the idea: one smaller entry for each house. An unfiltered rowstore index still contains entries for null dates. COUNT(*) can count those entries too. A filtered index that omits required rows cannot supply the whole-table count.

A full rowstore index scan still does work proportional to the index it reads. On four hundred million rows, repeating it every thirty seconds can be expensive. Check existing indexes before adding one just for counting; another index also costs storage and write work.

The Fast Answer

If the number does not have to be exact, do not read the data at all. SQL Server already keeps a count in its metadata.

SELECT SUM(p.rows) AS RowCounts
FROM sys.partitions AS p
WHERE p.object_id = OBJECT_ID('dbo.Orders')
  AND p.index_id IN (0, 1);

This reads catalog metadata without scanning the table’s rows. It is usually much cheaper for a large table. It is not a promise of instant completion.

For an ordinary disk-based table, index_id 0 identifies the heap and 1 identifies the clustered index. The filter selects that base storage, and SUM includes all its partitions. It avoids adding the nonclustered indexes as extra copies of the rows.

Why SUM? These views keep a separate row count for each partition. SUM adds those counts to return one total for the table. For example, partitions with 100, 200, and 300 rows give a total of 600. For a table with just one partition, SUM is optional, but keeping it makes the query work for both cases.

Drop that line and a table with two full nonclustered indexes can report 600,000 instead of 200,000. That happened in the recorded test: three structures represented the same rows. Filtered indexes can make the overcount less tidy.

The dynamic management view below offers another approximate count, with space information available alongside it. Both it and sys.partitions document their row counts as approximate.

SELECT SUM(row_count) AS RowCounts
FROM sys.dm_db_partition_stats
WHERE object_id = OBJECT_ID('dbo.Orders')
  AND index_id IN (0, 1);

Run these queries in the database containing dbo.Orders. If the result is NULL, check the name and metadata permissions rather than treating it as an empty table. These are whole-table counts, not counts for a WHERE condition.

On SQL Server 2022 and later, the DMV requires VIEW DATABASE PERFORMANCE STATE and VIEW SECURITY DEFINITION. Earlier versions require VIEW DATABASE STATE and VIEW DEFINITION.

For rows and space together, use EXEC sys.sp_spaceused N'dbo.Orders';. Its normal report is metadata-based too. The optional updateusage check adds work and should not be part of every dashboard refresh.

How Approximate Is Approximate

This is the part that decides whether you can use it.

Metadata counts can match a query count, as they did in the recorded test. That does not turn an approximate contract into an exact one. They also cannot tell you which rows belong to a particular load or report.

My rule is simple: use metadata for a rough size indicator. Use a query with the right filters when the result must drive a decision or prove a reconciliation.

A capacity report or a rough dashboard tile can use metadata. Proving that last night’s load completed needs load-specific evidence. An unchanged total might hide missing rows and duplicates.

For a reconciliation on a changing table, isolation matters too. COUNT(*) counts the rows its execution sees. It does not automatically freeze the table at one instant.

SQL Server’s row-versioning isolation options can provide a consistent statement or transaction snapshot when configured appropriately. Agree on the reporting cutoff. Adding NOLOCK can allow dirty, missing, or repeated reads and defeats an accuracy requirement.

What the Ten People Actually Told Me

A small-town letter board sign outside a brick town hall at dusk reading WHAT IS THE NUMBER FOR?

Nobody asked me the question back.

Ten experienced people, and not one said what do you need it for. They answered immediately, because it sounds like a question with one answer, and the questions that sound simple are the ones we stop interrogating.

These are two different jobs. Counting rows exactly, and knowing roughly how big a table is, only happen to be phrased the same way in English. Pick the wrong one and it costs you your accuracy, or a walk through every page holding four hundred million rows.

So next time somebody asks you for the fastest way, ask them the question nobody asked me. What is the number for?

There is no fastest way to count rows, there is only the fastest way to answer the question you actually had, and nobody ever says which one that is.

Published by Pinal Dave on SQLAuthority. More of my work at pinaldave.com.


Discover more from SQL Authority with Pinal Dave

Subscribe to get the latest posts sent to your email.

SQL Index, SQL Performance, SQL Server
Previous Post
AI Database Schemas: Good SQL, Tables That Age Badly

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.