Search This Blog

Add Row number to Select Query in SQL

You can add a row Number to sql Select query using Row Number Function 

Below is the table script with Example

CREATE TABLE #SQL
(
[Numbers] varchar(40)
)
INSERT INTO #SQL VALUES('One');
INSERT INTO #SQL VALUES('Two');
INSERT INTO #SQL VALUES('Three');
INSERT INTO #SQL VALUES('Four');
INSERT INTO #SQL VALUES('Five')

Case 1st -Showing Row Number in Select Query in SQL


select *,ROW_NUMBER()over( order by (select 1)) as Row_Num from #SQL

Output

Numbers Row_Num
One    1
Two    2
Three 3
Four 4
Five 5

Case 2nd Adding a Row Number column in Table

Just add an identity field column in the  table

alter table #sql
add Row_Num int Identity(1,1)

Select * from #SQL

Output

Numbers Row_Num
One    1
Two    2
Three 3
Four 4
Five 5

No comments:

Post a Comment