I have a SQL Server 2008 query
SELECT TOP 10 *
FROM T
WHERE ...
ORDER BY ...
I'd like to get also the total number of the rows. The obious way is to make a second query
SELECT COUNT(*)
FROM T
WHERE ...
ORDER BY ...
Is there an efficient method?
Thanks
No.
SQL Server
doesn't keepCOUNT(*)
in metadata likeMyISAM
, it calculates it every time.UPDATE: If you need an estimate, you can use statistics metadata:
where
@primary_key
is your table's primary key name.This will return the
COUNT(*)
from last statistics update.What is in this answer seems to work:
https://stackoverflow.com/a/19125458/16241
Basically you do a:
TotalCount will have the total number of rows. It is listed on each row though.
When I tested this the query plan showed the table only being hit once.
Do you want a second query?
OR
Or (Edit: using WITH)
Remove the ORDER BY clause from the 2nd query as well.