Home > Database > Mysql Tutorial > How to Limit Rows in Oracle Queries After Ordering?

How to Limit Rows in Oracle Queries After Ordering?

Linda Hamilton
Release: 2025-01-25 08:41:12
Original
298 people have browsed it

How to Limit Rows in Oracle Queries After Ordering?

Restricting Result Sets in Ordered Oracle Queries

Oracle's ROWNUM pseudocolumn differs from MySQL's LIMIT clause; ROWNUM is assigned before the ORDER BY clause is processed. Therefore, directly using ROWNUM won't limit rows after ordering. To achieve this, utilize a subquery:

<code class="language-sql">SELECT *
FROM (SELECT * FROM emp ORDER BY sal DESC)
WHERE ROWNUM <= n;</code>
Copy after login

This approach first orders the emp table by salary (sal) descending, then the outer query uses ROWNUM to restrict the output to the top n rows.

For more intricate scenarios requiring both upper and lower bounds, a nested subquery is necessary:

<code class="language-sql">SELECT *
FROM (SELECT a.*, ROWNUM rnum
      FROM (SELECT * FROM your_table ORDER BY your_column) a
      WHERE ROWNUM <= :MAX_ROW_TO_FETCH)
WHERE rnum >= :MIN_ROW_TO_FETCH;</code>
Copy after login

Oracle 12c and Beyond

Oracle 12c (and later versions) offer a more streamlined syntax using FETCH FIRST and OFFSET:

<code class="language-sql">SELECT *
FROM sometable
ORDER BY name
FETCH FIRST 10 ROWS ONLY;</code>
Copy after login

This directly limits the result set to the first 10 rows after ordering by name. To specify an offset (e.g., skip the first 20 rows and retrieve the next 10), use the OFFSET clause:

<code class="language-sql">SELECT *
FROM sometable
ORDER BY name
OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY;</code>
Copy after login

Refer to the official Oracle documentation for comprehensive examples and performance optimization strategies.

The above is the detailed content of How to Limit Rows in Oracle Queries After Ordering?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template