Home > Database > Mysql Tutorial > How Can I Efficiently Retrieve the Top N Highest Values in Oracle SQL?

How Can I Efficiently Retrieve the Top N Highest Values in Oracle SQL?

DDD
Release: 2025-01-09 13:52:40
Original
527 people have browsed it

How Can I Efficiently Retrieve the Top N Highest Values in Oracle SQL?

Extracting Top N Records in Oracle SQL

Need to fetch a specific number of rows with the highest or lowest values in a column? Oracle's analytic functions, like RANK() and DENSE_RANK(), provide efficient solutions.

For example, to identify the top five highest-earning employees, use RANK():

<code class="language-sql">SELECT * FROM (
  SELECT empno, sal, RANK() OVER (ORDER BY sal DESC) AS rnk
  FROM emp
)
WHERE rnk <= 5;</code>
Copy after login

DENSE_RANK() offers a variation, eliminating gaps in ranking caused by ties:

<code class="language-sql">SELECT * FROM (
  SELECT empno, sal, DENSE_RANK() OVER (ORDER BY sal DESC) AS rnk
  FROM emp
)
WHERE rnk <= 5;</code>
Copy after login

The best approach depends on your specific needs.

ROW_NUMBER() assigns a unique rank to each row, but it arbitrarily removes ties, which might not be suitable for all scenarios.

<code class="language-sql">SELECT * FROM (
  SELECT empno, sal, ROW_NUMBER() OVER (ORDER BY sal DESC) AS rnk
  FROM emp
)
WHERE rnk <= 5;</code>
Copy after login

While a non-analytic method using ROWNUM exists, it's less reliable due to potential inconsistencies and is generally less preferred. The analytic function methods above provide more robust and predictable results.

The above is the detailed content of How Can I Efficiently Retrieve the Top N Highest Values in Oracle SQL?. 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