Rank Scores SQL Challenge - Oracle Solution

1. Introduction

This blog post will demonstrate how to rank scores in an Oracle database, a typical requirement in many data analysis and reporting tasks.

Problem

The objective is to create an Oracle SQL query that assigns a rank to each score in a database table. The rank should be determined based on the score value, in descending order.

Database Table:

Scores Table:
id score
1 300
2 250
3 200

3. Oracle Solution

SELECT
    id,
    score,
    DENSE_RANK() OVER (ORDER BY score DESC) as rank
FROM Scores;

Output:

id score rank
1 300 1
2 250 2
3 200 3

Explanation:

1. The DENSE_RANK() window function is used to calculate the rank of each score.

2. Scores are ordered in descending order for ranking.

3. DENSE_RANK() assigns consecutive ranks to distinct scores, with no gaps in the ranking sequence.

4. This method is ideal for ranking when you want to ensure consecutive ranks even in the presence of tied scores.


Comments