Hi,
It is possible using a trick:
drop table test;
create table test(id int);
insert into test values(1), (10), (3), (2);
select rownum(), * from test order by id; -- incorrect
select rownum, * from (select * from test order by id); -- correct
> current behavior of rownum in h2 is incorrect
I don't think it's incorrect. It matches the documentation, and as far
as I know it works like Oracle.
Anyway, this is quite a common problem. I will change the
documentation of ROWNUM to:
Returns the number of the current row. This function is supported for SELECT
statements, as well as for DELETE and UPDATE. The first row has the row number
1, and is calculated before ordering and grouping the result set.
To get the row number after ordering and grouping, use a subquery.
SELECT ROWNUM(), * FROM TEST;
SELECT ROWNUM(), * FROM (SELECT * FROM TEST ORDER BY NAME);
> MS SQL Server
"Row_Number() Over (Order By SalesOrderID)" - H2 doesn't support this
yet. But as more and more databases support it, it would be a good
idea to support it in H2 as well. As far as I know, Derby support
ROW_NUMBER() OVER() in the latest version, which is basically the same
as ROWNUM().
Regards,
Thomas