简体   繁体   中英

Does ROW_NUMBER() support OVER(ORDER BY 1)?

Below 2 statments giving 2 different results

SELECT t.EID,t.name, ROW_NUMBER() OVER(ORDER BY 1) AS ROW_NUM
  FROM ESWAR t
;
EID  NAME   ROW_NUM
2    Ram       1
1    Siva      2
3    Deva      3
SELECT t.EID, t.name,ROW_NUMBER() OVER(ORDER BY t.EID) AS ROW_NUM
  FROM ESWAR t
;
EID NAME    ROW_NUM
1   Siva       1
2   Ram    2
3   Deva       3

From "About SQL Functions" - "Analytic Functions" - "order_by_clause" :

Restrictions on the ORDER BY Clause

The following restrictions apply to the ORDER BY clause:

  • (...) Position ( position ) and column aliases ( c_alias ) are also invalid. (...)

So no, a column position cannot be used in an ORDER BY of an OVER clause. It is therefore simply treated as if it were an integer literal. And since that literal is the same for all rows, there is no defined order.

Just use the column name instead. It's clearer anyway -- that applies also to the ORDER BY clause of a SELECT plus it doesn't break, if the order of columns is changed.

You can't access a column name by position in the ORDER BY for an analytical (window) function.

order by 1 means " sort the result by the numeric value 1 " so it sorts by a constant not the value of a column.

It's essentially the same as order by 'foobar' or order by 99999

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM