Using Rowcount and Top keyword for controlling number of records returned

Hi,

Many a times in a query we need to limit down the number of records returned in the query. This can be done in two ways using the TOP keyword or the row count keyword.

Select top 10 from Table

This will return the top 10 records from the query. We can also make this dynamic by making the Value in Top keyword to come from a variable.

DECLARE @top INT
SET @top = 10
SELECT TOP(@top) * FROM Table

If using a stored procedure we can also pass this variable as a parameter in the procedure. This way we can easily control the number of record affected.

Another way to do the same stuff is to use the rowcount variable.

DECLARE @top INT
SET @top = 10
SET ROWCOUNT @top
SELECT * FROM Table
set rowcount 0

Remember converting the rowcount back to 0 is very important; otherwise all other query will follow the same rowcount as set earlier.

The drawback with rowcount is that in the future version this will not work with the delete and update statement in the future version of the SQL server, so its best to use the top keyword only.

Vikram

Share this post   Email it |  digg it! |  reddit! |  bookmark it!

Feedback

Posted on 7/18/2008 9:39:59 AM

Hi Vikram,

There are some minor syntax errors. Please modify the last example to:

DECLARE @top INT
SET @top = 10
SET ROWCOUNT @top
SELECT * FROM Table
set rowcount 0

Thanks for the blog. Keep up the good work.

Posted on 7/19/2008 10:31:22 PM

Hi Murali Sagi,
Thanks.. Updated

Posted on 8/15/2008 10:59:13 AM

Good Post

Posted on 8/29/2008 6:35:07 AM

Good One

Please post your comments:

Name:  
Email (optional): Your email address will not be posted.
URL (optional):
Comments: HTML will be ignored, URLs will be converted to hyperlinks  
Enter the text you see in the box:
 
Copyright © 2006 - 2008 Vikram Lakhotia