Click here to Skip to main content
15,890,609 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hello ,
I have a table test in which there are total 1000 record

when i select some fields which i want then it return 135 rows

SQL
select distinct 
column1,column2,column3,column4,column5 from test


now i want to add a column which represent row number like 1 2 3 ..... 135
Posted

The simplest way is to use TOP instruction.
SQL
SELECT TOP (135) <Field_list>
FROM TableName


Please, see: TOP (Transact-SQL)[^]

If you would like to add row number, use ROW_NUMBER()[^] function.
SQL
SELECT TOP (135) ROW_NUMBER() OVER(ORDER BY <FieldName>) AS RowNo, <Field_list>
FROM TableName


You can set the limit of rows via using ROW_NUMBER() function.
SQL
SELECT *
FROM (
    SELECT ROW_NUMBER() OVER(ORDER BY <FieldName>) AS RowNo, <Field_list>
    FROM TableName)
AS T 
WHERE RowNo<=135


In the same way, you can fetch data from defined range, for example:
SQL
DECLARE @rFrom INT = 136
DECLARE @rTo INT = 170
SELECT *
FROM (
    SELECT ROW_NUMBER() OVER(ORDER BY <FieldName>) AS RowNo, <Field_list>
    FROM TableName)
AS T 
WHERE RowNo BETWEEN @rFrom AND @rTo

I call it: 'custom pagination' ;)
 
Share this answer
 
v2
if u need also row no,try this
SQL
select top 135 column1,ROW_NUMBER() over(order by column1 asc) from table
 
Share this answer
 
v3
Comments
Garth J Lancaster 16-Oct-14 3:05am    
row_number() - nice .. I forgot that one
Rajesh waran 16-Oct-14 6:29am    
Thank u.
I usually find it easier to add an integer auto increment column when I define the table (sometimes its also the primary key) - that way

a) when I insert a new row I have a unique value
b) I can use the value as a key if I need to

you can do a sql modify table to add the column (I think, depending on 'which sql flavour/variant' you're using) - then you'd need a small cursor update program to update the table and set the value incrementally - its a PITA - you then have to maintain it for all new rows added etc .. easier to have the value auto incremented for you on an insert imho

as solution 4 points out, row_number() should do what you want

'g'
 
Share this answer
 
v2
SQL
Select Column1,Column2,ROW_NUMBER() OVER(ORDER BY Column1 asc)
From Test 
order by Column1 asc


Please accept the solution if get desired result
 
Share this answer
 
v2
SQL
select row_number() OVER(ORDER BY column1 asc) as newcolumn,column1,column2,column3,column4,column5
from table


i hope this is helpful
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900