Skip to main content

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:

sql
SELECT MAX(column_name) FROM table_name;

Where:

  • column_name is the name of the column you want to find the maximum value from
  • table_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_idproduct_namepricecategory
1Laptop1200.00Electronics
2Smartphone800.00Electronics
3Headphones150.00Electronics
4Office Chair250.00Furniture
5Desk350.00Furniture

To find the highest price in our products table:

sql
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:

sql
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:

sql
SELECT MAX(price) AS highest_electronics_price 
FROM products
WHERE category = 'Electronics';

Output:

highest_electronics_price
-------------------------
1200.00
sql
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:

sql
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_idcustomer_idorder_datetotal_amountnumber_of_items
11012023-01-151500.003
21022023-01-20800.002
31012023-02-052000.005
41032023-02-101200.004
sql
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

sql
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:

sql
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:

sql
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_idfirst_namelast_nameemail
101JohnSmith[email protected]
102JaneDoe[email protected]
103RobertWilliams[email protected]
sql
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_idproduct_idratingcomment
115Great laptop!
214Good value
32NULLNot received yet
433Decent quality
sql
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

sql
SELECT MAX(last_updated) AS last_update_time
FROM inventory;

Identifying Top Performers

sql
SELECT department, MAX(sales_amount) AS top_sales
FROM employee_performance
GROUP BY department;

Determining Price Ranges

sql
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

sql
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:

sql
-- 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:

sql
-- 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

  1. 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.

  2. Using the same employees table, write a query to find the employee(s) who earn the highest salary.

  3. Write a query that finds the most recent hire date for each department.

  4. 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! :)