Mysql Max
Overview
MySQL max() function is part of the aggregate function family which allows you to perform operations on multiple sets of values from multiple rows at the same time and returns a single value. MySQL max() function allows you to get the highest value from a specific column. It is mostly used to find the maximum value of attributes like maximum salary, maximum marks, or the latest date in a database.
In this article, we will go through the basic working of the max() function along with several examples to fully grasp the concept. So without wasting any time, let us get started.
Syntax of MySQL MAX() Function
The syntax for the MySQL max function is really simple and looks something like this
This function also supports one more optional syntax which looks something like this.
Now let us understand this syntax and parameters in detail in the next section
Parameters of MySQL MAX() Function
Expression: The MySQL max() function takes mostly this one parameter which signifies the expression or column or field that you want to find the maximum of. It can be anything from a column name, a mathematical expression, or a date/time data type supported by MySQL, such as INT, DECIMAL, FLOAT, DATE, TIME, DATETIME, TIMESTAMP, etc.
DISTINCT: This optional keyword is primarily used to remove duplicates from your data set so that you won't have to compare the same values from multiple rows in a column.
Over_clause: The over clause is an optional parameter. The over clause is only used when you haven't explicitly mentioned the DISTICT keyword in your MySQL max() function.
Return Value of MySQL MAX() Function
The MySQL MAX() function returns a single value, which is the maximum value found in the specified column or expression. The data type of the returned value depends on the data type of the input column or expression. For example, if the input column is of type INT, the returned value will be an INT, if the input column is of type DECIMAL, the returned value will be a DECIMAL, and so on.
Exceptions of MySQL MAX() Function
- It is important to note that if the input column or expression contains NULL values, the MAX() function will return NULL as the result. Therefore, it is necessary to handle NULL values appropriately in your queries to avoid unexpected results.
- Another thing to note here is that it operates on a single column or expression at a time and returns the maximum value found in that column or expression.
- The MAX() function ignores any NULL values in the input column or expression when determining the maximum value.
How does the MySQL MAX() Function Work?
The MySQL max() function is part of the aggregate function family in MySQL which is a collection of functions that work on an expression or a group of values from a column, apply logical calculations to them, and return the final answer. MySQL max() function is used to find the maximum value from an expression or a column in the same way. It takes in one parameter and that is the column that we are trying to find the maximum of. Then it goes through each row of our table and checks the corresponding value for the specified column. In the end, it returns the maximum value in that column.
For example, if you have a table that stores the salaries of every employee in your company, you can apply the max() function on the Salary column and it will return the employee with the highest salary.
We will look at some examples in the next section to fully grasp the concept.
Examples
So, we have seen the syntax for the MySQL max() function and we have also seen how the MySQL max() function works. Now it's time to understand the concept in detail by looking at some actual examples. In this section, you will see different cases where you can use the max() function and how to apply it. Let us get started
Example 1:
Using MySQL max() function
Let us look at a simple example first. let us consider the customer's table which looks something like this.
Customers
customer_id | first_name | last_name | age | country |
---|---|---|---|---|
1 | Johny | Doe | 31 | USA |
2 | Rob | Luna | 22 | USA |
3 | Dav | Robinson | 22 | UK |
4 | Jo | Reinhardt | 25 | UK |
5 | Betty | Jr. | 28 | UAE |
6 | Britny | Kolu | 23 | UK |
7 | Case | Richards | 23 | UK |
8 | Mitch | Van dao | 28 | USA |
9 | Jake | Higgins | 20 | USA |
10 | Hex | Doe | 24 | USA |
11 | Moly | Oper | 37 | UAE |
12 | Bob | Van | 47 | UAE |
Now let us say that we want to find the oldest customer in our table. We can do that with the help of MySQL max() like this.
Output
MAX(age) |
---|
47 |
As you can see, our query returns the highest value of age in our entire table.
Example 2:
Using MySQL max() function along with the GROUP BY clause
In the last example, we saw how we can use the max() function to find the oldest customer in our Customers table. But let us say that we are conducting a survey we want to find the oldest person from each country? Let us look at an example that does exactly that.
So our Customers table looks something like this.
Customers:
customer_id | first_name | last_name | age | country |
---|---|---|---|---|
1 | Johny | Doe | 31 | USA |
2 | Rob | Luna | 22 | USA |
3 | Dav | Robinson | 22 | UK |
4 | Jo | Reinhardt | 25 | UK |
5 | Betty | Jr. | 28 | UAE |
6 | Britny | Kolu | 23 | UK |
7 | Case | Richards | 23 | UK |
8 | Mitch | Van dao | 28 | USA |
9 | Jake | Higgins | 20 | USA |
10 | Hex | Doe | 24 | USA |
11 | Moly | Oper | 37 | UAE |
12 | Bob | Van | 47 | UAE |
Let's find the oldest person from each country
Output
MAX(age) | country |
---|---|
31 | USA |
25 | UK |
47 | UAE |
So as you can see, we can get the maximum age grouped by each country with the help of the MySQL max() function.
Example 3:
Using MySQL max() function along with the WHERE clause
Now Let us assume we want to calculate the Highest age of the person in the country USA. In that case, we can use the MySQL max() function along with the Where clause.
Customers:
customer_id | first_name | last_name | age | country |
---|---|---|---|---|
1 | Johny | Doe | 31 | USA |
2 | Rob | Luna | 22 | USA |
3 | Dav | Robinson | 22 | UK |
4 | Jo | Reinhardt | 25 | UK |
5 | Betty | Jr. | 28 | UAE |
6 | Britny | Kolu | 23 | UK |
7 | Case | Richards | 23 | UK |
8 | Mitch | Van dao | 28 | USA |
9 | Jake | Higgins | 20 | USA |
10 | Hex | Doe | 24 | USA |
11 | Moly | Oper | 37 | UAE |
12 | Bob | Van | 47 | UAE |
Output
Max(age) | country |
---|---|
31 | USA |
As you can see, we get the highest age in the USA.
Example 4:
Using MySQL max() function along with LENGTH() function
Let us now look at a slightly interesting example. Lets us assume that you work at an online store and you have a table that stores the information regarding all your products. The product table looks something like this.
Products
ProductID | ProductName | SupplierID | CategoryID | Unit | Price |
---|---|---|---|---|---|
1 | Chais | 1 | 1 | 10 boxes x 20 bags | 18 |
2 | Chang | 1 | 1 | 24 - 12 oz bottles | 19 |
3 | Aniseed Syrup | 1 | 2 | 12 - 550 ml bottles | 10 |
4 | Chef Anton's Cajun Seasoning | 2 | 2 | 48 - 6 oz jars | 22 |
5 | Chef Anton's Gumbo Mix | 2 | 2 | 36 boxes | 21.35 |
6 | Grandma's Boysenberry Spread | 3 | 2 | 12 - 8 oz jars | 25 |
7 | Uncle Bob's Organic Dried Pears | 3 | 7 | 12 - 1 lb pkgs. | 30 |
8 | Northwoods Cranberry Sauce | 3 | 2 | 12 - 12 oz jars | 40 |
9 | Mishi Kobe Niku | 4 | 6 | 18 - 500 g pkgs. | 97 |
10 | Ikura | 4 | 8 | 12 - 200 ml jars | 31 |
11 | Queso Cabrales | 5 | 4 | 1 kg pkg. | 21 |
12 | Queso Manchego La Pastora | 5 | 4 | 10 - 500 g pkgs. | 38 |
13 | Konbu | 6 | 8 | 2 kg box | 6 |
14 | Tofu | 6 | 7 | 40 - 100 g pkgs. | 23.25 |
15 | Genen Shouyu | 6 | 2 | 24 - 250 ml bottles | 15.5 |
16 | Pavlova | 7 | 3 | 32 - 500 g boxes | 17.45 |
17 | Alice Mutton | 7 | 6 | 20 - 1 kg tins | 39 |
18 | Carnarvon Tigers | 7 | 8 | 16 kg pkg. | 62.5 |
19 | Teatime Chocolate Biscuits | 8 | 3 | 10 boxes x 12 pieces | 9.2 |
20 | Sir Rodney's Marmalade | 8 | 3 | 30 gift boxes | 81 |
Now you want to find out the product with the longest name for some reason. You can do that by using the MySQL max() function in combination with another MySQL function called LENGTH(). The LENGTH() function returns the length of the expression provided to it.
Let us see what the code for the same looks like.
Output
ProductName | MaxLength |
---|---|
Uncle Bob's Organic Dried Pears | 33 |
As you can see, the MySQL max() function calculates the length of each product name and returns us the maximum length which is 31 for Uncle Bob's Organic Dried Pears.
Example 5:
Using MySQL max() function along with the HAVING clause
Now let us look at an example where we can use the Having clause along with the MySQL max() function. If you remember, having a clause is always used along with the group by clause.
Let us suppose that we have a suppliers table that looks something like this.
Suppliers
SupplierID | SupplierName | ContactName | Address | City | PostalCode | Country | Phone |
---|---|---|---|---|---|---|---|
1 | Exotic Liquid | Charlotte Cooper | 49 Gilbert St. | Londona | EC1 4SD | UK | (171) 555-2222 |
2 | New Orleans Cajun Delights | Shelley Burke | P.O. Box 78934 | New Orleans | 70117 | USA | (100) 555-4822 |
3 | Grandma Kelly's Homestead | Regina Murphy | 707 Oxford Rd. | Ann Arbor | 48104 | USA | (313) 555-5735 |
4 | Tokyo Traders | Yoshi Nagase | 9-8 Sekimai Musashino-shi | Tokyo | 100 | Japan | (03) 3555-5011 |
5 | Cooperativa de Quesos 'Las Cabras' | Antonio del Valle Saavedra | Calle del Rosal 4 | Oviedo | 33007 | Spain | (98) 598 76 54 |
6 | Mayumi's | Mayumi Ohno | 92 Setsuko Chuo-ku | Osaka | 545 | Japan | (06) 431-7877 |
7 | Pavlova, Ltd. | Ian Devlin | 74 Rose St. Moonie Ponds | Melbourne | 3058 | Australia | (03) 444-2343 |
8 | Specialty Biscuits, Ltd. | Peter Wilson | 29 King's Way | Manchester | M14 GSD | UK | (161) 555-4448 |
9 | PB Knäckebröd AB | Lars Peterson | Kaloadagatan 13 | Göteborg | S-345 67 | Sweden | 031-987 65 43 |
10 | Refrescos Americanas LTDA | Carlos Diaz | Av. das Americanas 12.890 | São Paulo | 5442 | Brazil | (11) 555 4640 |
11 | Heli Süßwaren GmbH & Co. KG | Petra Winkler | Tiergartenstraße 5 | Berlin | 10785 | Germany | (010) 9984510 |
12 | Plutzer Lebensmittelgroßmärkte AG | Martin Bein | Bogenallee 51 | Frankfurt | 60439 | Germany | (069) 992755 |
now, we are trying to find the maximum length of a supplier name in every country living in a city that contains an 'o' in its name. This sounds a little complex but we can get the desired result with the help of these simple MySQL queries.
Output:
SupplierName | City | Country | Maxlength |
---|---|---|---|
Pavlova, Ltd. | Melbourne | Australia | 13 |
Refrescos Americanas LTDA | São Paulo | Brazil | 25 |
Ma Maison | Montréal | Canada | 9 |
Escargots Nouveaux | Montceau | France | 18 |
Pasta Buttini s.r.l. | Salerno | Italy | 20 |
Mayumi's | Osaka | Japan | 8 |
Tokyo Traders | Tokyo | Japan | 13 |
Leka Trading | Singapore | Singapore | 12 |
Cooperativa de Quesos 'Las Cabras' | Oviedo | Spain | 34 |
PB Knäckebröd AB | Göteborg | Sweden | 16 |
Svensk Sjöföda AB | Stockholm | Sweden | 17 |
Exotic Liquid | Londona | UK | 13 |
We can notice that we get the name and length count of the name of each supplier which lives in a city containing the letter 'o' in its name in each country.
Example 6:
Using MySQL max() function along with nested subqueries
Now let us see how we can use the MySQL max() function along with the nested subqueries. Let us assume that we have an orders table that looks something like this.
OrderDetails
OrderDetailID | OrderID | ProductID | Quantity |
---|---|---|---|
1 | 10248 | 11 | 12 |
2 | 10248 | 42 | 10 |
3 | 10248 | 72 | 5 |
4 | 10249 | 14 | 9 |
5 | 10249 | 51 | 40 |
6 | 10250 | 41 | 10 |
7 | 10250 | 51 | 35 |
8 | 10250 | 65 | 15 |
9 | 10251 | 22 | 6 |
10 | 10251 | 57 | 15 |
11 | 10251 | 65 | 20 |
12 | 10252 | 20 | 40 |
13 | 10252 | 33 | 25 |
14 | 10252 | 60 | 40 |
15 | 10253 | 31 | 20 |
Output
max(productid) |
---|
72 |
In this example, we are using a nested query to get all the orderIDs in a particular range, and then out of those ids, we are getting the maximum productID by using the MySQL max() function.
Conclusion
- The MySQL MAX() function is a powerful tool for finding the maximum value in a column or expression in a MySQL database table.
- It is commonly used in various scenarios, such as finding the highest value, latest date, or maximum length of a string.
- It returns a single value and the return type of the return value is the same as the data type of the expression or column it is applied on.
- The MySQL MAX() function does not throw any exceptions as such. However, it is important to note that if the input column or expression contains NULL values, the MAX() function will return NULL as the result.
- The MySQL MAX() function operates on a single column or expression at a time and returns the maximum value found in that column or expression.
- MySQL max() function can be used in combination with several other MySQL clauses such as the group by clause, having clause, and also along with nested queries.
See also
With this, we have come to the end of this article about the MySQL max() function. But learning never stops and neither should you. So, if you want to sharpen your skills, check out these similar articles on scaler topics.