Home > Database > Mysql Tutorial > How to Limit Oracle Query Results After Ordering?

How to Limit Oracle Query Results After Ordering?

DDD
Release: 2025-01-25 08:32:09
Original
319 people have browsed it

How to Limit Oracle Query Results After Ordering?

Concisely Limiting Ordered Results in Oracle

Oracle's row limiting differs from simpler SQL dialects like MySQL. While MySQL uses LIMIT, Oracle employs the ROWNUM pseudocolumn. However, directly using ROWNUM in a WHERE clause before ORDER BY yields unpredictable results.

The Challenge: Ordering Before Limiting

The issue stems from ROWNUM's evaluation before the ORDER BY clause. This means you don't get the top N rows after sorting; instead, you get N arbitrary rows.

The Solution: Subqueries for Precise Control

To correctly limit rows after ordering, use a subquery:

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

This first orders the emp table by salary (sal) descending, then the outer query selects only the top 10 rows using ROWNUM.

Specifying Start and End Rows:

For more precise control, defining both upper and lower bounds requires nested subqueries:

<code class="language-sql">SELECT *
FROM (
  SELECT a.*, ROWNUM rnum
  FROM (
    SELECT * FROM emp ORDER BY sal DESC
  ) a
  WHERE ROWNUM <= 30
)
WHERE rnum >= 21;</code>
Copy after login

This retrieves rows 21-30 (inclusive) after sorting by salary.

Modern Oracle (12c and later): Simplified Syntax

Oracle 12c and later versions offer a cleaner approach:

<code class="language-sql">-- Top 10 results
SELECT *
FROM sometable
ORDER BY name
FETCH FIRST 10 ROWS ONLY;

-- Rows 20-30
SELECT *
FROM sometable
ORDER BY name
OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY;</code>
Copy after login

This FETCH FIRST and OFFSET syntax is significantly more readable and efficient for pagination. Use this method if your Oracle version supports it.

The above is the detailed content of How to Limit Oracle Query Results 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template