Rob Gonda's Blog

SQL: better than select count(*)

If you need to count all rows from a table without any conditional, there's a much better and faster way than select count(*). This code works with Microsoft SQL 2000 and 2005.

CREATE FUNCTION [dbo].[FASTCOUNT] (@Table sysname)

RETURNS INT

AS
BEGIN

  DECLARE @Rows int

  SELECT  @Rows = rows
  FROM sysindexes
  WHERE id = OBJECT_ID(@Table)
  AND indid < 2

  RETURN @Rows

END

p.s. I've been using this code for so long, I don't even remember who to give credit to :) thanks!

TrackBacks
There are no trackbacks for this entry.

Trackback URL for this entry:
http://www.robgonda.com/blog/trackback.cfm?86BF42A4-3048-7431-E492C327D2F8A6C4

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
This blog is running version 5.9.003. Contact Blog Owner