6

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?

unknownuser
  • 790
  • 9
  • 16

2 Answers2

6

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
William Brendel
  • 31,712
  • 14
  • 72
  • 77
5

This will return the rank as rownum

SELECT @rownum := @rownum + 1 rownum, 
       t.* 
  FROM (SELECT @rownum:=0) r, 
       (SELECT * FROM students ORDER BY gpa DESC) t;
Evan Mulawski
  • 54,662
  • 15
  • 117
  • 144
Vinko Vrsalovic
  • 330,807
  • 53
  • 334
  • 373