Wednesday, October 19, 2011

How to fetch first 10 rows in SQL Server 2008 R2 / 2005

It is pretty simple to fetch first n records in SQL Server 2008 R2. Following is the syntax and example SQL Query to fetch the first 10 rows from a SQL Server 2008 R2 / 2005 database.

Syntax:

SELECT TOP (n) * FROM

--n could be any unsigned bigint value
-- You may also use TOP n without parenthesis. Using TOP keyword without parenthesis gives backward compatibility with SQL Server 2000 but I guess most don't require such a backward compatibility. So it is recommended by Microsoft to use TOP with parenthesis.


For advanced users: 

n is actually an expression. That is, it is capable of performing calculations to derive the final number of records to be retrieved.

Optionally you may also use PERCENT keyword next to the n to denote the input for fetching number of records is on percentage. That is, the following Example 2 will fetch 10 records from a table containing 100 records. When n is used as percentage, n will be treated as float.

Example 1:

SELECT TOP (10) * FROM  employees



Example 2:

SELECT TOP (10) PERCENT * FROM employees


It is as simple as above. I am publishing this on my blog because this is the most frequent database related question most people asked me.

2 comments:

  1. yar bahitop command to chal hi nahi rahah h.

    ReplyDelete
  2. "yar bahitop command to chal hi nahi rahah h."

    Please provide more information.

    ReplyDelete

Share your comments