SQL: Ranking use Rank() Function

 

Subject: Rank in SQL


Here is a simple example to use the function called "Rank" in SQL.


Suppose that you have the following table:


Student ID | Name | Score |



You are asked to rank and order the students based on their scores.


This is a possible solution to this problem:


SELECT Name, Score, RANK() OVER (ORDER BY Score DESC) AS Ranking

FROM Students;


So the results look like this:


| Name  | Score | Ranking |

| ------- | ----- | ------- |

| David   | 92  | 1    |

| Alice   | 90   | 2    |

| Charlie | 90   | 2    |

| Eva    | 88   | 4    |

| Bob    | 85   | 5    |

Popular Posts