SQLite Forum

Using constant integer with row_number order by
Login

Using constant integer with row_number order by

(1) By chrdev on 2021-02-27 13:49:25 [link] [source]

SQLite version 3.34.1 2021-01-20 14:10:07

Hi,

I'm trying to use window function row_number(), when I put a constant integer with ORDER BY, found some weird things.
Here are test runs:

CREATE TABLE tbl (id INTEGER PRIMARY KEY);
INSERT INTO tbl VALUES(1),(2);


SELECT id,row_number() OVER (ORDER BY "id" DESC) FROM tbl ORDER BY 1;

expected and real output:
1|2
2|1


SELECT id,row_number() OVER (ORDER BY 1 DESC) FROM tbl ORDER BY 1;

expected output:
1|2
2|1

real output:
1|1
2|2


SELECT id,row_number() OVER (ORDER BY 0) FROM tbl ORDER BY 1;

expected:
Prompt error: ORDER BY term out of range - should be between 1 and 2

real output:
1|1
2|2

SELECT id,row_number() OVER (ORDER BY 1000) FROM tbl ORDER BY 1;

expected:
Prompt error: ORDER BY term out of range - should be between 1 and 2

real output:
1|1
2|2

So is there anything regarding special ORDER BY clause processing in the doc that I missed, so could it be a bug?

Much thanks!

(2) By Larry Brasfield (larrybr) on 2021-02-27 14:51:34 in reply to 1 [link] [source]

Consult the doc for The ORDER BY clause, paragraph 5, item 1.

(3) By Keith Medcalf (kmedcalf) on 2021-02-27 15:17:43 in reply to 1 [link] [source]

The ORDER BY clause inside the OVER clause of a window function is not the ORDER BY of a select and as such there are no "output columns" from the projection by which the window can be sorted.

In other words it is working as intended, designed, and written. The "number" is just a number (constant), not a reference to a projection result column.

(4) By chrdev on 2021-02-27 15:57:36 in reply to 3 [source]

Thanks a lot for this clarification. I think the difference is very important yet very easy to miss by an average user. It would be nice if Window Functions doc contains these sentences.