Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TOP versus SET ROWCOUNT

Is there a difference in performance between TOP and SET ROWCOUNT or do they just get executed in the same manner?

like image 811
Garry Shutler Avatar asked Jan 22 '09 11:01

Garry Shutler


People also ask

What is set Rowcount?

Setting the SET ROWCOUNT option causes most Transact-SQL statements to stop processing when they have been affected by the specified number of rows. This includes triggers. The ROWCOUNT option does not affect dynamic cursors, but it does limit the rowset of keyset and insensitive cursors.

How do I use set rowcount?

The ROWCOUNT Set Function causes the server to stop the query processing after the specified number of records is returned. One may limit the number of records returned by all subsequent SELECT statements within the session by using the keyword SET ROWCOUNT.

What is the difference between count () and Rowcount ()?

So, @@RowCount is used to check number of rows affected only after a query execution. But Count(*) is a function, which will return number of rows fetched from the SELECT Query only. After SELECT statement also giving number of row retrived from the query.

What is @@ rowcount?

Data manipulation language (DML) statements set the @@ROWCOUNT value to the number of rows affected by the query and return that value to the client. The DML statements may not send any rows to the client.


2 Answers

Yes, functionally they are the same thing. As far as I know there are no significant performance differences between the two.

Just one thing to note is that once you have set rowcount this will persist for the life of the connection so make sure you reset it to 0 once you are done with it.


EDIT (post Martin's comment)

The scope of SET ROWCOUNT is for the current procedure only. This includes procedures called by the current procedure. It also includes dynamic SQL executed via EXEC or SP_EXECUTESQL since they are considered "child" scopes.

Notice that SET ROWCOUNT is in a BEGIN/END scope, but it extends beyond that.

create proc test1
as
begin
    begin
    set rowcount 100
    end
    exec ('select top 101 * from master..spt_values')
end
GO

exec test1
select top 102 * from master..spt_values

Result = 100 rows, then 102 rows

like image 107
Andrew Hare Avatar answered Sep 20 '22 16:09

Andrew Hare


One more note about performance, according to BOL:

As a part of a SELECT statement, the query optimizer can consider the value of expression in the TOP or FETCH clauses during query optimization. Because SET ROWCOUNT is used outside a statement that executes a query, its value cannot be considered in a query plan.

Article on BOL

Meaning there might be actually performance difference in these.

like image 44
ulath Avatar answered Sep 19 '22 16:09

ulath