Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually specify starting value for Row_Number()

I want to define the start of ROW_NUMBER() as 3258170 instead of 1.

I am using the following SQL query

SELECT ROW_NUMBER() over(order by (select 3258170))  as 'idd'. 

However, the above query is not working. When I say not working I mean its executing but its not starting from 3258170. Can somebody help me?

The reason I want to specify the row number is I am inserting Rows from one table to another. In the first Table the last record's row number is 3258169 and when I insert new records I want them to have the row number from 3258170.

like image 240
Huzaifa Avatar asked Mar 04 '13 20:03

Huzaifa


People also ask

How do I start a row number from a specific value in SQL?

Discussion: If you'd like to number each row in a result set, SQL provides the ROW_NUMBER() function. This function is used in a SELECT clause with other columns. After the ROW_NUMBER() clause, we call the OVER() function.

How do I assign a row number in SQL?

To add a row number column in front of each row, add a column with the ROW_NUMBER function, in this case named Row# . You must move the ORDER BY clause up to the OVER clause. SELECT ROW_NUMBER() OVER(ORDER BY name ASC) AS Row#, name, recovery_model_desc FROM sys.

Can we use WHERE clause in ROW_NUMBER?

The ROW_NUMBER function cannot currently be used in a WHERE clause. Derby does not currently support ORDER BY in subqueries, so there is currently no way to guarantee the order of rows in the SELECT subquery.

Can ROW_NUMBER be used without ORDER BY?

The row_number() window function can be used without order by in over to arbitrarily assign a unique value to each row.


2 Answers

Just add the value to the result of row_number():

select 3258170 - 1 + row_number() over (order by (select NULL)) as idd 

The order by clause of row_number() is specifying what column is used for the order by. By specifying a constant there, you are simply saying "everything has the same value for ordering purposes". It has nothing, nothing at all to do with the first value chosen.

To avoid confusion, I replaced the constant value with NULL. In SQL Server, I have observed that this assigns a sequential number without actually sorting the rows -- an observed performance advantage, but not one that I've seen documented, so we can't depend on it.

like image 80
Gordon Linoff Avatar answered Sep 21 '22 02:09

Gordon Linoff


I feel this is easier

ROW_NUMBER() OVER(ORDER BY Field) - 1 AS FieldAlias (To start from 0) ROW_NUMBER() OVER(ORDER BY Field) + 3258169 AS FieldAlias (To start from 3258170) 
like image 33
Tom McDonough Avatar answered Sep 25 '22 02:09

Tom McDonough