SQL Aggregate Function MAX()
In SQL, the MAX()
function is an aggregate function that returns the maximum value in a set of values. The function takes a single argument, which is the name of the column or expression to be evaluated.
Here is an example of using the MAX()
function to find the highest salary in a employees
table:
SELECT MAX(salary) AS max_salary FROM employees;
In this example, the MAX()
function is used to find the highest value in the salary
column of the employees
table. The AS
keyword is used to alias the column name as max_salary
.
The MAX()
function can also be used with the GROUP BY
clause to find the maximum value for each group in a table. For example, consider the following sales
table:
+---------+-------+ | product | sales | +---------+-------+ | A | 100 | | A | 200 | | B | 150 | | B | 250 | +---------+-------+
To find the highest sales value for each product, we can use the following query:
SELECT product, MAX(sales) AS max_sales FROM sales GROUP BY product;
In this example, the MAX()
function is used with the GROUP BY
clause to find the highest sales value for each unique value in the product
column. The result of the query is a table with two columns: product
and max_sales
. The MAX()
function is applied to the sales
column for each group of rows that share the same product
value.