SQL Server MAX() Function
In SQL Server, the MAX()
function is an aggregate function used to calculate the maximum value in a specified column or expression.
Syntax
The basic syntax of the MAX()
function is as follows:
MAX(expression)
where expression
is the column or expression to calculate the maximum value.
Usage
The MAX()
function is typically used to calculate the maximum value in a specified column. For example, it can be used to find the maximum order amount, highest sales revenue, or maximum inventory level in a table.
Examples
Here are two examples of using the MAX()
function.
Example 1
Suppose we have the following sales table:
order_id | customer_id | order_total |
---|---|---|
1 | 1001 | 50 |
2 | 1002 | 75 |
3 | 1001 | 100 |
4 | 1003 | 125 |
The following SQL statement can be used to calculate the maximum order amount in the orders table:
SELECT MAX(order_total) AS max_order_total
FROM orders;
The result is:
max_order_total |
---|
125 |
Example 2
Suppose we have the following products table:
product_id | product_name | unit_price |
---|---|---|
1 | Product A | 10.5 |
2 | Product B | 15.2 |
3 | Product C | 12.8 |
4 | Product D | 9.9 |
The following SQL statement can be used to calculate the maximum unit price in the products table:
SELECT MAX(unit_price) AS max_unit_price
FROM products;
The result is:
max_unit_price |
---|
15.2 |
Conclusion
By using the MAX()
function, we can easily find the maximum value in a specified column, which can help with data analysis and decision-making.