Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate columns in Oracle query using row limiting clause

Since Oracle 12c, we can finally use the SQL standard row limiting clause like this:

SELECT * FROM t FETCH FIRST 10 ROWS ONLY

Now, in Oracle 12.1, there was a limitation that is quite annoying when joining tables. It's not possible to have two columns of the same name in the SELECT clause, when using the row limiting clause. E.g. this raises ORA-00918 in Oracle 12.1

SELECT t.id, u.id FROM t, u FETCH FIRST 10 ROWS ONLY

This is a restriction is documented in the manual for all versions 12.1, 12.2, 18.0:

enter image description here

The workaround is obviously to alias the columns

SELECT t.id AS t_id, u.id AS u_id FROM t, u FETCH FIRST 10 ROWS ONLY

Or to resort to "classic" pagination using ROWNUM or window functions.

Curiously, though, the original query with ambiguous ID columns runs just fine from Oracle 12.2 onwards. Is this a documentation bug, or an undocumented feature?

like image 267
Lukas Eder Avatar asked Aug 09 '18 13:08

Lukas Eder


People also ask

Can we use limit in Oracle?

Oracle Database does not have the LIMIT clause.

How do I change constraints to allow duplicate values?

Solution 2: Change the constraint to allow for duplicates If you find that that rule is incorrect, you can change the constraint to say that the combination of first_name, last_name, and date_of_birth must be unique. To do this, you need to drop and recreate the constraint.

Why Rownum 2 is not valid in Oracle?

Oracle's ROWNUM starts on 1 and is only incremented when assigned to a row that passes the WHERE condition. Since you're filtering on ROWNUM=2, ROWNUM=1 doesn't pass the WHERE condition, and ROWNUM is therefore never assigned to a row and incremented to 2.


1 Answers

Seems in this case when you are using the row limiting clause, Oracle internally calling the ROW_NUMBER() function where it using the column name in OVER clause Like ROW_NUMBER OVER(ORDER BY ID). because of this you are getting the ORA-00918 error.

like image 152
Biswanath Avatar answered Nov 09 '22 04:11

Biswanath