Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find max value and its associated field values in SQL?

Tags:

sql

Say I have a list of student names and their marks. I want to find out the highest mark and the student, how can I write one select statement to do that?

like image 931
Steve Avatar asked Jun 01 '11 04:06

Steve


1 Answers

Assuming you mean marks rather than remarks, use:

select name, mark
from students
where mark = (
    select max(mark)
    from students
)

This will generally result in a fairly efficient query. The subquery should be executed once only (unless your DBMS is brain-dead) and the result fed into the second query. You may want to ensure that you have an index on the mark column.

like image 153
paxdiablo Avatar answered Sep 19 '22 15:09

paxdiablo