Max and Min in SQL

Published on

Let's say we have a database table named orders with columns: id, name, and cost.

idnamecost
1John Doe134.00
2Eve Marcus146.00
3Lucy Tomlin20.00
4Bill Carson118.00
5John Doe102.00
6Lucy Tomlin90.00
7Lucy Tomlin34.00
8Bill Carson122.00

In our application we might want to find the most expensive order, this is a perfect use case for the MAX aggregate function. Here's what our query would look like:

SELECT MAX(cost) as most_expensive FROM orders

And here's the result:

most_expensive
146.00

We can also find the least expensive order, by altering our query to this:

SELECT MIN(cost) as least_expensive FROM orders

And here's the result:

least_expensive
20.00

But we can take this even further, what if we wanted find the most expensive order for each person? We can alter our original query to include the order name and then group on it. So our new query looks like this:

SELECT name, MAX(cost) as most_expensive FROM orders GROUP BY name;

And this is our result:

namemost_expensive
John Doe134.00
Eve Marcus146.00
Lucy Tomlin90.00
Bill Carson122.00