Ranking queries in Oracle

 Ranking queries in Oracle 

In Oracle, you can perform ranking queries using the `RANK()`, `DENSE_RANK()`, and `ROW_NUMBER()` analytic functions. These functions allow you to assign a ranking to each row based on a specified ordering.


Here's a basic example of each ranking function:

1. RANK() Function:

SELECT emp_id, emp_name, salary,

       RANK() OVER (ORDER BY salary DESC) AS salary_rank
FROM employees;

This query assigns ranks to employees based on their salary in descending order. If there are ties in salary, employees with the same salary will receive the same rank, and the next rank will be skipped.


2. DENSE_RANK() Function:

SELECT emp_id, emp_name, salary,

       DENSE_RANK() OVER (ORDER BY salary DESC) AS salary_dense_rank
FROM employees;


Similar to `RANK()`, the `DENSE_RANK()` function assigns ranks to employees based on their salary in descending order. However, it does not skip ranks in case of ties. For example, if multiple employees have the same salary, they will all receive the same rank, and the next rank will be consecutive.


3. ROW_NUMBER() Function:

SELECT emp_id, emp_name, salary,
       ROW_NUMBER() OVER (ORDER BY salary DESC) AS salary_row_number
FROM employees;

The `ROW_NUMBER()` function assigns a unique sequential number to each row based on the specified ordering. Unlike `RANK()` and `DENSE_RANK()`, it does not handle ties in any special way. If multiple rows have the same value for the ordering expression, they will receive distinct row numbers.


Choose the appropriate ranking function based on your specific requirements for handling ties and the desired behavior of the ranking results.

Post a Comment

And that's all there is to it!

If anyone has any other questions or requests for future How To posts, you can either ask them in the comments or email me. Please don't feel shy at all!

I'm certainly not an expert, but I'll try my hardest to explain what I do know and research what I don't know.

Previous Post Next Post