SQL MAX Function
Introduction
The SQL MAX function is one of the most useful aggregate functions in SQL. It allows you to find the highest or maximum value in a specified column of data. Whether you need to find the most expensive product, the largest order amount, or the most recent date in your database, the MAX function provides a simple and efficient way to retrieve this information.
In this tutorial, you'll learn:
- What the MAX function is and how it works
- Basic syntax and usage
- How to combine MAX with GROUP BY
- Real-world applications
- Common pitfalls and best practices
Basic Syntax and Usage
The MAX function uses the following syntax:
SELECT MAX(column_name) FROM table_name;
Where:
column_name
is the name of the column you want to find the maximum value fromtable_name
is the name of the table containing that column
Simple Example
Let's start with a basic example. Imagine we have a table called products
with the following data:
product_id | product_name | price | category |
---|---|---|---|
1 | Laptop | 1200.00 | Electronics |
2 | Smartphone | 800.00 | Electronics |
3 | Headphones | 150.00 | Electronics |
4 | Office Chair | 250.00 | Furniture |
5 | Desk | 350.00 | Furniture |
To find the highest price in our products table:
SELECT MAX(price) FROM products;
Output:
MAX(price)
---------
1200.00
The query returns 1200.00, which is the price of the most expensive product (the laptop).
Custom Column Name
When working with aggregate functions, it's often helpful to rename the result column using an alias:
SELECT MAX(price) AS highest_price FROM products;
Output:
highest_price
-------------
1200.00
Using MAX with WHERE Clause
You can combine the MAX function with a WHERE clause to find the maximum value within a subset of your data:
SELECT MAX(price) AS highest_electronics_price
FROM products
WHERE category = 'Electronics';
Output:
highest_electronics_price
-------------------------
1200.00
SELECT MAX(price) AS highest_furniture_price
FROM products
WHERE category = 'Furniture';
Output:
highest_furniture_price
-----------------------
350.00
MAX Function with GROUP BY
The MAX function becomes even more powerful when combined with the GROUP BY clause. This allows you to find the maximum value within different groups of data.
Let's continue with our products example:
SELECT category, MAX(price) AS highest_price
FROM products
GROUP BY category;
Output:
category | highest_price
-------------|--------------
Electronics | 1200.00
Furniture | 350.00
This query returns the highest price for each product category.
Multiple MAX Functions
You can use multiple MAX functions in a single query to find the maximum values of different columns:
Let's assume we have an orders
table:
order_id | customer_id | order_date | total_amount | number_of_items |
---|---|---|---|---|
1 | 101 | 2023-01-15 | 1500.00 | 3 |
2 | 102 | 2023-01-20 | 800.00 | 2 |
3 | 101 | 2023-02-05 | 2000.00 | 5 |
4 | 103 | 2023-02-10 | 1200.00 | 4 |
SELECT
MAX(total_amount) AS highest_order_amount,
MAX(number_of_items) AS max_items_in_order,
MAX(order_date) AS most_recent_order
FROM orders;
Output:
highest_order_amount | max_items_in_order | most_recent_order
---------------------|-------------------|------------------
2000.00 | 5 | 2023-02-10
This query gives us the highest order amount, the maximum number of items in any order, and the most recent order date. Note that these maximums might come from different rows in the table.
Finding the Row with the Maximum Value
Sometimes you want to find not just the maximum value but the entire row that contains that maximum value. There are several approaches to doing this.
Using a Subquery
SELECT *
FROM products
WHERE price = (SELECT MAX(price) FROM products);
Output:
product_id | product_name | price | category
-----------|--------------|---------|----------
1 | Laptop | 1200.00 | Electronics
This returns the complete row for the most expensive product.
Finding Max Values per Group
To find the complete information about the most expensive product in each category:
SELECT p1.*
FROM products p1
INNER JOIN (
SELECT category, MAX(price) AS max_price
FROM products
GROUP BY category
) p2 ON p1.category = p2.category AND p1.price = p2.max_price;
Output:
product_id | product_name | price | category
-----------|--------------|---------|----------
1 | Laptop | 1200.00 | Electronics
5 | Desk | 350.00 | Furniture
MAX Function with Dates
The MAX function works with date and datetime columns as well. The "maximum" of a date column is the most recent date.
For example, using our orders table from earlier:
SELECT MAX(order_date) AS most_recent_order
FROM orders;
Output:
most_recent_order
-----------------
2023-02-10
MAX Function with Text Columns
The MAX function can also be used with text columns. When applied to strings, MAX returns the string that would be last in alphabetical (or lexicographical) order.
Let's say we have a customers
table:
customer_id | first_name | last_name | |
---|---|---|---|
101 | John | Smith | [email protected] |
102 | Jane | Doe | [email protected] |
103 | Robert | Williams | [email protected] |
SELECT MAX(last_name) FROM customers;
Output:
MAX(last_name)
--------------
Williams
Since "Williams" comes after "Smith" and "Doe" alphabetically, it's returned as the maximum.
NULL Values and the MAX Function
The MAX function automatically ignores NULL values when determining the maximum. If all values in the column are NULL, then MAX returns NULL.
For example, if we have a reviews
table with some NULL ratings:
review_id | product_id | rating | comment |
---|---|---|---|
1 | 1 | 5 | Great laptop! |
2 | 1 | 4 | Good value |
3 | 2 | NULL | Not received yet |
4 | 3 | 3 | Decent quality |
SELECT MAX(rating) FROM reviews;
Output:
MAX(rating)
-----------
5
The NULL value is ignored, and 5 is returned as the maximum rating.
Real-World Applications
Finding the Most Recent Record
SELECT MAX(last_updated) AS last_update_time
FROM inventory;
Identifying Top Performers
SELECT department, MAX(sales_amount) AS top_sales
FROM employee_performance
GROUP BY department;
Determining Price Ranges
SELECT
category,
MIN(price) AS min_price,
MAX(price) AS max_price,
MAX(price) - MIN(price) AS price_range
FROM products
GROUP BY category;
Finding the Highest Performer in Each Region
SELECT r.region_name, e.employee_name, e.sales
FROM employees e
INNER JOIN (
SELECT region_id, MAX(sales) AS max_sales
FROM employees
GROUP BY region_id
) max_sales ON e.sales = max_sales.max_sales
INNER JOIN regions r ON e.region_id = r.region_id;
Common Pitfalls and Best Practices
1. Combining MAX with Other Columns
One common mistake is to select additional columns without including them in the GROUP BY clause:
-- Incorrect query
SELECT product_name, MAX(price)
FROM products;
This will cause an error in most database systems because product_name
is not in an aggregate function or the GROUP BY clause.
The correct way would be:
-- Correct query
SELECT product_name, price
FROM products
WHERE price = (SELECT MAX(price) FROM products);
2. Performance Considerations
MAX functions typically require a full table scan or index scan to find the maximum value. For large tables, ensure that columns used in MAX functions are properly indexed for better performance.
3. Using MAX in Joins
When using MAX in combination with JOINs and GROUP BY, the query can become complex. Breaking down complex queries into simpler parts or using CTEs (Common Table Expressions) can make them more readable and maintainable.
Summary
The SQL MAX function is a powerful aggregate function that helps you find the highest value in a column. You've learned how to:
- Use MAX to find the highest numeric, date, or text value
- Combine MAX with WHERE clauses to filter data
- Use MAX with GROUP BY to find maximums within groups
- Find entire rows containing maximum values
- Handle NULL values with MAX
- Apply MAX in real-world scenarios
- Avoid common pitfalls when using MAX
Practice Exercises
-
Create a table called
employees
with columns for employee_id, name, department, and salary. Insert sample data and write a query to find the highest salary in each department. -
Using the same
employees
table, write a query to find the employee(s) who earn the highest salary. -
Write a query that finds the most recent hire date for each department.
-
Create a
sales
table with columns for sale_id, product_id, sale_date, and amount. Write a query to find the highest sale amount for each month.
Additional Resources
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)