The MAX()
function in SQL is a powerful aggregate function used to retrieve the maximum (highest) value from a specified column in a table. It is commonly employed for analyzing data to identify the largest numeric value, the latest date, or other maximum values in various datasets. The MAX()
function automatically excludes NULL
values from its computation, ensuring accuracy.
In this article, we will cover the syntax, use cases, sample tables, and practical examples with detailed explanations of how to use the MAX()
function effectively. Whether we are a beginner or an advanced SQL user, this guide will help us understand and apply the MAX()
function confidently.
Syntax:
SELECT MAX(column_name)
FROM table_name
[WHERE condition];
Key Terms:
column_name
: The column for which you want to find the maximum value.table_name
: The table containing the data.condition
(optional): Filters rows before calculating the maximum value.
Examples of SQL MAX() Function
In this section, we will demonstrate the usage of the MAX() function with examples using a two sample tables. Product Prices table contains product IDs and their corresponding prices. The Sales
table contains sales data with sale IDs, product IDs, sale dates, and amounts.
Product Prices Table
Product Prices TableSales Table
Sales TableExample 1: Find the Maximum Price in a Table
To find the highest price in the product_prices
table. This query is simple yet effective for identifying the most expensive product in the dataset. It excludes NULL
values, ensuring only valid prices are considered.
Query:
SELECT MAX(price) AS [Highest Price]
FROM product_prices;
Output
Explanation: The MAX(price)
function evaluates all the values in the price
column and returns the largest value, $199.99
.
Example 2: Find the Maximum Sale Amount
To determine the highest sale amount from the Sales
table. This query is commonly used in sales data analysis to find the most significant transaction in terms of value. It helps businesses track their peak sales performances.
Query:
SELECT MAX(amount) AS [Highest Sale]
FROM Sales;
Output:
Explanation: The MAX(amount)
function scans the amount
column in the Sales
table and identifies the largest sale, which is $1500.00
Example 3: Use MAX() with a Condition
Find the maximum price for products under a specific category, e.g., Electronics: This query is valuable for targeted analysis such as identifying the product with highest price within a specific category.
Query:
SELECT MAX(price) AS [Highest Price in Electronics]
FROM product_prices
WHERE category = 'Electronics';
Output:
Highest Price in Electronics |
---|
149.95 |
Explanation: The WHERE
clause filters rows to include only products in the 'Electronics' category. The MAX(price)
function then calculates the maximum price within this subset.
Example 4: Find the Latest Sale Date
To find the most recent sale date in the Sales
table. This query is particularly useful for tracking the last activity in a dataset, such as identifying the latest transaction or update.
Query:
SELECT MAX(sale_date) AS [Latest Sale Date]
FROM Sales;
Output:
Latest Sale Date |
---|
2023-02-01 |
Explanation: The MAX(sale_date)
function evaluates all dates in the sale_date
column and returns the most recent one, 2023-02-01
Example 5: Using MAX() with GROUP BY
Find the highest sale amount for each product. This query is helpful for analyzing performance metrics at the product level, allowing businesses to track the best-performing products.
Query:
SELECT product_id, MAX(amount) AS [Highest Sale]
FROM Sales
GROUP BY product_id;
product_id | Highest Sale |
---|
1 | 500.00 |
2 | 1500.00 |
3 | 300.00 |
Explanation: The GROUP BY
clause groups rows by product_id
, and the MAX(amount)
function calculates the highest sale amount for each group.
Example 6: Using MAX() in Subqueries
Retrieve details of the product with the highest price. The main query retrieves the full record associated with this maximum price, providing detailed information about the most expensive product.
Query:
SELECT *
FROM product_prices
WHERE price = (SELECT MAX(price) FROM product_prices);
Output:
Explanation: The subquery (SELECT MAX(price) FROM product_prices)
determines the highest price ($199.99
). The main query fetches all records matching this price.
Conclusion
The MAX()
function in SQL is a fundamental tool for data analysis, enabling users to find the highest value in a column. It can be used independently or in combination with other SQL clauses like WHERE
, GROUP BY
, and subqueries to handle complex data requirements. By mastering the MAX()
function, WE can efficiently analyze and summarize data in various scenarios, such as identifying maximum prices, latest dates, or highest scores.
Similar Reads
PL/SQL MAX() Function
The PL/SQL MAX() function is an essential aggregate function in Oracle databases, enabling users to efficiently determine the largest value in a dataset. Whether working with numerical data, dates, or strings, the MAX() function is flexible and widely applicable.In this article, we will provide a de
4 min read
SQLite MAX() Function
MAX function is a type of Aggregate Function available in SQLite, which is primarily used to find out the maximum value from a given set (a column that is passed as its parameter). Other than that, the MAX function can also be used with other Aggregate functions like HAVING, GROUP BY, etc to sort or
5 min read
SQL LAG() Function
The LAG() function in SQL is one of the most powerful and flexible tools available for performing advanced data analysis. It is often used to compare rows, calculate differences, and tracks trends in a dataset, especially for time-series data. If we are working with sales, stock prices, or even empl
5 min read
SQL MIN() Function
The MIN() function in SQL is a powerful tool that allows us to determine the smallest or lowest value from a specified column or expression. It is widely used in data analysis to extract minimum values for decision-making, reporting, and business insights. This function automatically excludes NULL v
8 min read
PLSQL | MOD Function
The MOD function is an inbuilt function in PLSQL which is used to return the remainder when a is divided by b. Its formula is m - n * \left\lfloor\dfrac{m}{n}\right\rfloor. Syntax: MOD(a, b) Parameters Used: This function accepts two parameters a and b. This function gives remainder as the output wh
2 min read
SQL LTRIM() Function
The SQL LTRIM() function is an essential tool used in data cleaning and manipulation tasks. This function helps remove unwanted leading spaces or specific characters from the left side of a string or string expression. It's commonly used to tidy up data by eliminating unnecessary spaces or character
4 min read
PL/SQL Functions
PL/SQL functions are reusable blocks of code that can be used to perform specific tasks. They are similar to procedures but must always return a value. A function in PL/SQL contains:Function Header: The function header includes the function name and an optional parameter list. It is the first part o
4 min read
PLSQL | LPAD Function
The PLSQL LPAD function is used for padding the left-side of a string with a specific set of characters. a prerequisite for this is that string shouldn't be NULL. The LPAD function in PLSQL is useful for formatting the output of a query. The LPAD function accepts three parameters which are input_str
2 min read
MySQL IF( ) Function
The MySQL IF() function is a control flow function that returns different values based on the result of a condition. IF() Function in MySQLThe IF() function in MySQL returns a value if the condition is TRUE and another value if the condition is FALSE. The MySQL IF() function can return values that c
2 min read
PLSQL | LN Function
The LN function is an inbuilt function in PLSQL which is used to return the natural logarithm of a given input number. The natural logarithm of a number is the logarithm of that number to the base e, where e is the mathematical constant approximately equal to 2.718. This is written using the notatio
2 min read