Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Efficient Row Count

I'm looking for an efficent method of returning the number of rows a select query will return. Which objects are fastest/most efficient? The queries will be run against Sql Server.
[185 byte] By [joewmaki] at [2007-11-11 8:51:02]
# 1 Re: Efficient Row Count
If you're using a DataTable to hold the results of your query you can simply use the Count property of the Rows collection.
pclement at 2007-11-11 21:46:57 >
# 2 Re: Efficient Row Count
If you're not using a DataTable, you can execute a SELECT COUNT(*) query with the same WHERE clause to determine the number of records likely to be returned. This number will change, however, if other users perform INSERT or DELETE operations between your SELECT COUNT query and your record-returning query.
Phil Weber at 2007-11-11 21:47:57 >
# 3 Re: Efficient Row Count
If you're not using a DataTable, you can execute a SELECT COUNT(*) query with the same WHERE clause to determine the number of records likely to be returned. This number will change, however, if other users perform INSERT or DELETE operations between your SELECT COUNT query and your record-returning query.

I wish it were that simple :) The SQL string could be a simple select, a stored procedure or complex union query. basicly whatever we need to do to generate the required report. I need to get a recordcount occasionally and wanted to use the fastest approach. I thought a datareader had the least overhead, but I'd need to step through the datareader in order to get a count. I decided a dataset was the simplest approach, I can query the dataset.tables(0).rows.count.

Considering that having to return the resultset twice will only have a noticible performance hit occasionally, I decided simple is better <g>
joewmaki at 2007-11-11 21:49:01 >