Tuesday, April 1, 2008

How does one select the TOP N rows from a table?

After Oracle 9i there is the RANK() and DENSE_RANK() functions which can be used to determine TOP N rows.

Below is the examples to find the top 5 employees based on their salary.

Way 1: Using RANK()

SELECT employee_name, salary
FROM ( SELECT employee_name, salary, RANK() OVER (ORDER BY salary DESC) salary_rank
FROM employee )
WHERE salary_rank <= 5;


Way 2: Using Dense_Rank()

SELECT employee_name, salary
FROM ( SELECT employee_name, salary, DENSE_RANK() OVER (ORDER BY salary DESC) salary_dense_rank
FROM employee )
WHERE salary_dense_rank <= 5;


Way3: Using inner query

This is an example of using an inner-query with an ORDER BY clause:

SELECT *
FROM (SELECT * FROM employee ORDER BY salary DESC)
WHERE ROWNUM < 5;


Way 4: Using count distinct combination

SELECT *
FROM employee e
WHERE 5 >= (SELECT COUNT(DISTINCT salary)
FROM employee b
WHERE b.salary >= e.salary)
ORDER BY salary DESC;


Related Documents
How does one select EVERY Nth row from a table?

Can one retrieve only the Nth row from a table?

Can one retrieve only rows X to Y from a table?

1 comment:

  1. Get the top 10 employees based on their salary
    SELECT ename, sal
    FROM ( SELECT ename, sal, RANK() OVER (ORDER BY sal DESC) sal_rank
    FROM emp )
    WHERE sal_rank <= 10;

    Hi,
    I am not a hardcore database guy. but when i am googling for the top N rows, i found your blogging. As per the above query, it may fetch more than 10 rows if SAL column is having few duplicate rows, but our requirment is to fetch ONLY the TOP N (i.e. only 10 rows). Because RANK() function assigns the same rank to SAL if it is having the duplicate values.please correct me if i am wrong

    ReplyDelete