Wednesday, May 28, 2008

Finding rows associated with a maximum value in MySQL

This example shows how to display the rows associated with a maximum value (or minimum) of a column. To illustrate this we'll look at the following scenario:

We have a MySQL table called "employees" and we want to display the employees whose salaries (kept in the "salary" column) are equal to the maximum salary in the table. To do this, we must first find the maximum value:

SELECT (@x:=MAX(salary)) FROM employees;

Next, we'll want to display all the information available on people who have that salary. Again, we do this using another SELECT instruction:

SELECT * FROM employees WHERE salary=@x;

This is a simple example however a tough one to find on the Internet. Many thanks to Radu for helping me on this.


2 comments:

Anonymous said...

Why are people only interested in top and bottom situations? Being average feels just as good. :p

Coshoi said...

Well there's an avg function for that as well :)

(removed my previous comment because of a typo).