Restricting Result Sets by ROWNUM

Posted: August 11, 2010 in SQL Server 2005

If you want to restrict a result set by ROWNUM (similar to Oracle’s ROWNUM function), you will have to use a build in function in SQL Server call ROW_NUMBER() as follows:

-- Create temp table
CREATE TABLE #Test (col1 VARCHAR(50) PRIMARY KEY,
                    col2 VARCHAR(100)
                   );

-- Insert records into temp table
 INSERT INTO #Test (col1, col2) VALUES ('Amit', 'Blah');
 INSERT INTO #Test (col1, col2) VALUES ('Rob',  'Blah Blah');
 INSERT INTO #Test (col1, col2) VALUES ('Iain', 'Blah');

-- Use analytics to get the rownum based on an order by clause
SELECT col1, col2, rownum
FROM  (SELECT col1, col2, ROW_NUMBER() OVER (ORDER BY col1) as rownum
       FROM   #Test) #Test
WHERE  rownum < 3;

-- Drop temp table
DROP TABLE #Test;
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s