Connecting Tech Pros Worldwide Forums | Help | Site Map

retrieve n number of rows from table

Site Addict
 
Join Date: Feb 2007
Posts: 553
#1: Jun 22 '09
How do i retreive 10 rows from a table using SQL

SELECT Names from Customers... how do i change it to retrieve only 'n' number of rows?

Please suggest an easy method
Thanks

code green's Avatar
Expert
 
Join Date: Mar 2007
Location: England
Posts: 1,083
#2: Jun 22 '09

re: retrieve n number of rows from table


Expand|Select|Wrap|Line Numbers
  1. SELECT TOP 10 Names from Customers .... ORDER BY
nbiswas's Avatar
Member
 
Join Date: May 2009
Location: India
Posts: 34
#3: Jun 26 '09

re: retrieve n number of rows from table


CASE 1

If you want to retrieve only the first 10 or 20 rows, then the go with TOP N statement.

Where N indicates any number

e.g.

Expand|Select|Wrap|Line Numbers
  1. Select TOP 10 * from table_name
CASE 2
If you want to retrieve only the last 10 or 20 rows, then the go with TOP N .. ORDER BY DESCstatement

e.g.
Expand|Select|Wrap|Line Numbers
  1. Select TOP N * from table_name ORDER BY COLUMN_NAME DESC
CASE 3

If you want to retrieve the records in between(say 20th to 30th out of 100 records).

Use ROW_NUMBER() function.

I have a table(say CHOOSERECORDS) with only 1 column(say RECORDS) of type int

Now I have inserted values from 1 to 100 there.

Next I want to select records from say 20 to 30. The query is here

Expand|Select|Wrap|Line Numbers
  1. SELECT A.RECORDS FROM (SELECT ROW_NUMBER() OVER (ORDER BY RECORDS) AS ROWID,RECORDS FROM CHOOSERECORDS) A 
  2. WHERE A.ROWID BETWEEN 20 AND 30
Hope this answers your question.
Reply

Tags
select rows