Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to generate ranks in MYSQL?

Tags:

sql

mysql

What's the best way to get the rank of the rows in addition to the row data in MYSQL?

For instance, say I have a list of students and I want to rank on the GPA. I know I can order by the GPA, but what's the quickest way to have MYSQL return the rank as well in the rowdata I get back?

like image 479
unknownuser Avatar asked Jan 10 '09 14:01

unknownuser


People also ask

How do I create a dense rank in MySQL?

The rank of a row is increased by one from the number of distinct rank values which come before the row. The syntax of the DENSE_RANK() function is as follows: DENSE_RANK() OVER ( PARTITION BY <expression>[{,<expression>...}] ORDER BY <expression> [ASC|DESC], [{,<expression>...}] )

How do you rank data in SQL?

To partition rows and rank them by their position within the partition, use the RANK() function with the PARTITION BY clause. SQL's RANK() function allows us to add a record's position within the result set or within each partition. In our example, we rank rows within a partition.


1 Answers

This will return the students' rank, student ID, and GPA.

set @rownum := 0;
SELECT @rownum := @rownum + 1 AS rank, student_id, gpa 
    FROM `students` ORDER BY gpa DESC
like image 88
William Brendel Avatar answered Oct 05 '22 06:10

William Brendel