2023-05-03 11:06:20 +02:00
== Why is this an issue?
2021-05-19 01:18:45 +00:00
Oracle's ``++ROWNUM++`` is a pseudo column that numbers the rows in a result set. Unfortunately, it numbers the rows in the set _before_ ordering is applied. So combining the two in the same query won't get you the results you expect. Instead, you should move your selection and ordering into a subquery, and use ``++ROWNUM++`` only on the outer query.
2023-05-03 11:06:20 +02:00
=== Noncompliant code example
2021-05-19 01:18:45 +00:00
2022-02-04 17:28:24 +01:00
[source,sql]
2021-05-19 01:18:45 +00:00
----
SELECT fname, lname, deptId
FROM employee
WHERE rownum <= 10
ORDER BY salary -- Noncompliant
----
2023-05-03 11:06:20 +02:00
=== Compliant solution
2021-05-19 01:18:45 +00:00
2022-02-04 17:28:24 +01:00
[source,sql]
2021-05-19 01:18:45 +00:00
----
SELECT *
FROM ( SELECT fname, lname, deptId
FROM employee
ORDER BY salary
)
WHERE rownum <= 10
----
2021-06-02 20:44:38 +02:00
2021-06-03 09:05:38 +02:00
ifdef::env-github,rspecator-view[]
2021-09-20 15:38:42 +02:00
'''
== Implementation Specification
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== Message
Order your results in a subquery and apply "rownum" at the level of the outer query.
=== Highlighting
* primary: order by
* secondary: rownum|row_number()
2021-09-20 15:38:42 +02:00
2021-06-08 15:52:13 +02:00
'''
2021-06-02 20:44:38 +02:00
== Comments And Links
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== on 27 Jun 2017, 15:57:56 Pierre-Yves Nicolas wrote:
\[~ann.campbell.2] The title may be misleading. Some other possibilities:
* "ROWNUM should not be used at the same query level as ORDER BY"
* or "ROWNUM should not be used with ORDER BY without a subquery"
=== on 27 Jun 2017, 16:09:55 Ann Campbell wrote:
\[~pierre-yves.nicolas]: "ORDER BY" should not be applied to queries that use "ROWNUM"
?
=== on 27 Jun 2017, 16:26:11 Pierre-Yves Nicolas wrote:
\[~ann.campbell.2] "ORDER BY should not be applied on top of a ROWNUM-based WHERE"? :)
2021-06-03 09:05:38 +02:00
endif::env-github,rspecator-view[]