Connecting Tech Pros Worldwide Help | Site Map

retrieve n number of rows from table

  #1  
Old June 22nd, 2009, 10:12 AM
Site Addict
 
Join Date: Feb 2007
Posts: 553
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
  #2  
Old June 22nd, 2009, 02:29 PM
code green's Avatar
Expert
 
Join Date: Mar 2007
Location: England
Posts: 1,063
Provided Answers: 2

re: retrieve n number of rows from table


Expand|Select|Wrap|Line Numbers
  1. SELECT TOP 10 Names from Customers .... ORDER BY
  #3  
Old June 26th, 2009, 04:57 AM
nbiswas's Avatar
Newbie
 
Join Date: May 2009
Location: India
Posts: 10

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


Similar Threads
Thread Thread Starter Forum Replies Last Post
Copy Row Of Data From Table to Table In Same DB pbd22 answers 10 June 5th, 2007 07:05 PM
retrieve rows from datagridview into a separate datatable? Rich answers 3 May 18th, 2006 06:05 AM
Getting the index number of a column in a datarow in a strongly typed dataset... Programatix answers 3 December 12th, 2005 07:55 AM
Help to optimize procedure (concatenation of rows) Juraj Longauer answers 0 July 19th, 2005 10:40 PM