Manually specify starting value for Row_Number() Manually specify starting value for Row_Number() sql-server sql-server

Manually specify starting value for Row_Number()


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.


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)


Sometimes....

The ROW_NUMBER() may not be the best solution especially when there could be duplicate records in the underlying data set (for JOIN queries etc.). This may result in more rows returned than expected. You may consider creating a SEQUENCE which can be in some cases considered a cleaner solution.i.e.:

CREATE SEQUENCE myRowNumberId      START WITH 1      INCREMENT BY 1 GO  SELECT NEXT VALUE FOR myRowNumberId  AS 'idd' -- your queryGODROP SEQUENCE myRowNumberId; -- just to clean-up after ourselvesGO

The downside is that sequences may be difficult to use in complex queries with DISTINCT, WINDOW functions etc. See the complete sequence documentation here.