MySQL numeric functions
MySQL string functions
MySQL Date/Time functions
MySQL aggregate functions
MySQL flow control functions
The MAX()
function in MySQL is an aggregate function that returns the maximum value in a set of values. You can use the MAX()
function to select the highest (maximum) value in a column.
Syntax:
SELECT MAX(column_name) FROM table_name WHERE condition;
Example:
Let's say we have a table named orders
, which contains the following data:
OrderID | Product | Quantity |
---|---|---|
1 | Apples | 5 |
2 | Bananas | 10 |
3 | Oranges | 7 |
4 | Apples | 15 |
5 | Bananas | 8 |
6 | Oranges | 20 |
If we want to find the highest quantity ordered, we can use the MAX()
function like this:
SELECT MAX(Quantity) AS MaxQuantity FROM orders;
The MaxQuantity
after AS
is an alias which will be used as the column name for the result set.
This will return:
MaxQuantity |
---|
20 |
Using MAX()
in a column with text data:
You can use the MAX()
function on a column containing text data to get the maximum value according to the column's collation.
For example, if you want to find the product that is last in alphabetical order, you could use the MAX()
function like this:
SELECT MAX(Product) AS LastProduct FROM orders;
This will return:
LastProduct |
---|
Oranges |
Using MAX()
with GROUP BY
:
You can use the MAX()
function in conjunction with the GROUP BY
clause to get the maximum value for each group.
For example, if you want to find the maximum quantity ordered of each product, you could do this:
SELECT Product, MAX(Quantity) AS MaxQuantity FROM orders GROUP BY Product;
This will return:
Product | MaxQuantity |
---|---|
Apples | 15 |
Bananas | 10 |
Oranges | 20 |
This shows the maximum quantity ordered for each product in the orders
table.
MySQL MAX Function Example:
SELECT MAX(column_name) AS max_value FROM table_name;
How to Use MAX Function in MySQL:
SELECT MAX(price) AS max_price FROM products;
Finding the Maximum Value with MAX in MySQL:
SELECT MAX(salary) AS highest_salary FROM employees;
Grouping and MAX Function in MySQL:
SELECT department_id, MAX(salary) AS max_salary FROM employees GROUP BY department_id;
MAX Function with WHERE Clause in MySQL:
SELECT MAX(total_amount) AS max_order_amount FROM orders WHERE status = 'Shipped';
Using MAX Function for Date and Time Values in MySQL:
SELECT MAX(order_date) AS latest_order_date FROM orders;
Handling NULL Values with MAX Function in MySQL:
SELECT MAX(IFNULL(salary, 0)) AS max_salary FROM employees;
Examples of Using MAX Function in MySQL Queries:
SELECT MAX(stock_quantity) AS max_stock FROM products;
SELECT department_id, MAX(hire_date) AS latest_hire_date FROM employees GROUP BY department_id;