Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Row_Number() function in Where Clause without ORDER BY?

I found a bunch of questions on this topic with nice solutions but none of them actually deal with what to do if the data is not to be ordered in one specific way. For instance, the following query:

WITH MyCte AS  (     select   employee_id,              RowNum = row_number() OVER ( order by employee_id )     from     V_EMPLOYEE      ORDER BY Employee_ID ) SELECT  employee_id FROM    MyCte WHERE   RowNum > 0 

works well if the data is to be ordered by employee_id. But what if my data does not have any specific order but the row numbers themselves act as an ID? My goal is to write a query like this (with the Row_Number() function having no ORDER BY clause):

WITH MyCte AS  (     select   employee_id,              RowNum = row_number() OVER ( <PRESERVE ORIGINAL ORDER FROM DB> )     from     V_EMPLOYEE      ORDER BY Employee_ID ) SELECT  employee_id FROM    MyCte WHERE   RowNum > 0 

EDIT: Upon Googling, I figured out that this is not really possible. Can some suggest a workaround for this?

like image 753
Legend Avatar asked Jun 17 '11 18:06

Legend


People also ask

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.

Can we use row number without ORDER BY in SQL Server?

Normally you can use ROW_NUMBER() as in the example below along with ORDER BY. If you try to use the ROW_NUMBER() function without ORDER BY clause, you will get an error as seen below. The function 'ROW_NUMBER' must have an OVER clause with ORDER BY .

Can ROW_NUMBER be used in WHERE clause?

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.

Does row number need ORDER BY clause?

The function 'ROW_NUMBER' must have an OVER clause with ORDER BY. The ORDER BY clause determines the sequence in which the rows are assigned their unique ROW_NUMBER within a specified partition. It is required.” So apparently the window order clause is mandatory for the ROW_NUMBER function in SQL Server.


1 Answers

Just in case it is useful to someone else. I just figured it out from elsewhere:

WITH MyCte AS  (     select   employee_id,              RowNum = row_number() OVER (ORDER BY (SELECT 0))     from     V_EMPLOYEE      ORDER BY Employee_ID ) SELECT  employee_id FROM    MyCte WHERE   RowNum > 0 
like image 107
Legend Avatar answered Sep 26 '22 10:09

Legend