Open In App

SQL | Top-N Queries

Top-N Analysis in SQL deals with How to limit the number of rows returned from ordered sets of data in SQL. 
Top-N queries ask for the n smallest or largest values of a column. Both smallest and largest values sets are considered Top-N queries. Following this type of searching technique could save lot of time and complexities. Top-N analysis are useful in cases where the need is to display only the n bottom-most or the n top- 
most records from a table based on a condition. This result set can be used for further analysis. 

For example, using Top-N analysis we can perform the following types of queries: 
 



 

Performing Top-N Analysis



Following the below mentioned queries we can easily understand the working of Top-N analysis in SQL: 
Syntax: 
 

SELECT [column_list], ROWNUM
FROM (SELECT [column_list]
      FROM table_name
      ORDER BY Top-N_clolumn)
WHERE ROWNUM<=N;

We will perform the various commands on the following table named Employee: 

 

Example 1: 
 

Input : 
SELECT ROWNUM as RANK, first_name, last_name, employee_id, salary
FROM (SELECT salary, first_name, last_name, employee_id
      FROM Employee
      ORDER BY salary)
WHERE ROWNUM<=3;

Output : 
 

Explanation: In the above SQL statement, the required fields are displayed for employees with top 3 lowest salaries. The result is displayed in increasing order of their salaries. 

Example 2: 
 

Input : 
SELECT ROWNUM as RANK, first_name, employee_id, hire_date
FROM (SELECT first_name, employee_id, hire_date
      FROM Employee
      ORDER BY hire_date)
WHERE ROWNUM<=3;

Output : 
 

Explanation: In the above SQL statement, the required fields are displayed for those 3 employees who were hired earliest. The result is displayed in increasing order of their hire date. 

 

Different styles for using Top-N analysis

 

Input : 
SELECT first_name, last_name
FROM (SELECT first_name, last_name
      FROM Employee
      ORDER BY salary DESC)
WHERE ROWNUM<=4;

Input :
SELECT employee_id, first_name, salary
FROM   (SELECT employee_id, first_name, salary, rownum AS rnum
        FROM   (SELECT employee_id, first_name, salary
                FROM Employee
                ORDER BY salary)
        WHERE rownum<=4)
WHERE  rnum>=2;

Input : 
SELECT dpartment_id, first_name
FROM (SELECT dpartment_id, first_name,
      RANK() OVER (ORDER BY dpartment_id DESC) AS rnum 
      FROM Employee)
WHERE rnum<=3;

Input : 
SELECT dpartment_id, first_name
FROM (SELECT dpartment_id, first_name,
      DENSE_RANK() OVER (ORDER BY dpartment_id DESC) AS rnum 
      FROM Employee)
WHERE rnum<=3;

Input : 
SELECT dpartment_id, first_name
FROM (SELECT dpartment_id, first_name,
      ROW_NUMBER() OVER (ORDER BY dpartment_id DESC) AS rnum 
      FROM Employee)
WHERE rnum<=4;

 

Article Tags :