The following question was posed to ITKnowledge Exchange members. Read the problem then peruse some of the responses....
By submitting your email address, you agree to receive emails regarding relevant topic offers from TechTarget and its partners. You can withdraw your consent at any time. Contact TechTarget at 275 Grove Street, Newton, MA.
Click here for the complete discussion.
Member "manickam" writes: "To determine the number of rows we use a count(*) function on a table, but doing so hurts the performance of our tables with large rows. We will use sysindexes to get the number of rows in table, but sometimes the results of the two queries differs. Can anyone help?
eg: table_name = table1
number of rows = 20
query1: select count(*) from table1; results:20
select rows from sysindexes where name = table1;
Member "rlreid" writes: "Depends. sp_spaceused is a possibility, with caveat.
In my shop, the first question I would ask is, "Wy are you counting the rows"? I don't know your application but it is rare to actually need an exact count of the rows and it does take a table scan.
The sysindexes approach has nothing to recommend it. If an estimate is good enough, use "sp_spaceused" and look at the "rows" value. This is not always an exact count of the number of rows, but its close enough for a lot of things.
As to avoiding count? Some folks use "count" instead of "exists." If "exists" is all you need, it is much faster. Are you doing a count to do memory allocation? If the table is so big, why put it in local memory? And if there's a good answer to that, why not do reallocs as needed, say every 10,000 rows?
You need to understand why you want to do a count, and then see if you can avoid it. If you must have an exact count, then you must scan the table and count the rows (and be sure nothing changes while you do whatever it is you want to do with the count).
Otherwise, use sp_spaceused, or redesign to not need the count."
Member "Eolianne" writes: "It would be slightly faster if you did a SELECT COUNT(TABLEID) FROM TABLE instead of SELECT COUNT(*) if your table has a lot of columns."
Member "yfellow" writes: "DBCC UPDATEUSAGE. Please refer to BOL for more information."