π SQL MAX() Function β How to Get the Highest Value in a Column
The SQL MAX() function is a powerful aggregate function that returns the maximum (largest) value in a column. Itβs commonly used in data analysis for tasks like finding the highest salary, most recent transaction, or the largest order.
This tutorial will teach you:
- β
What the SQL
MAX()function does - π‘ Syntax and behavior
- π Practical SQL examples
- β οΈ Tips and common mistakes
β What is SQL MAX()?
The MAX() function returns the highest value in a column across a set of rows. It works with numeric, date, and text-based (alphabetical) values.
π§ Syntax
SELECT MAX(column_name)
FROM table_name
WHERE condition;
You can also use MAX() in combination with:
GROUP BYto find the max in each categoryJOINsto get related recordsHAVINGto filter group-level maximums
π SQL MAX() Function Examples
π§ͺ Example 1: Find the Highest Salary
SELECT MAX(salary) AS highest_salary
FROM employees;
βοΈ This returns the largest value in the salary column.
π§ͺ Example 2: Find the Latest Order Date
SELECT MAX(order_date) AS latest_order
FROM orders;
π Useful in tracking recent transactions or events.
π§ͺ Example 3: Get Highest Score per Student
SELECT student_id, MAX(score) AS top_score
FROM test_results
GROUP BY student_id;
π Perfect for reporting top performance by category.
π§ͺ Example 4: MAX() on Text Values (Alphabetically)
SELECT MAX(last_name) AS max_name
FROM employees;
π °οΈ Returns the last name that is alphabetically last.
β οΈ Common SQL MAX() Mistakes to Avoid
| Mistake | Solution |
|---|---|
Using MAX() without GROUP BY on multiple columns | Use GROUP BY with all non-aggregated columns |
| Expecting MAX() to return multiple rows | MAX() returns only one value per group |
| Ignoring NULLs | MAX() automatically ignores NULLs |
π― Real-World Use Cases for SQL MAX()
- π’ HR: Get the highest salary in a department
- π E-Commerce: Get the biggest order per customer
- π Events: Find the most recent login or activity
- π Analytics: Get the peak performance metrics
β SQL MAX() with GROUP BY
SELECT department_id, MAX(salary) AS highest_salary
FROM employees
GROUP BY department_id;
This query returns the highest salary in each department.
π§ Pro Tip: Use MAX() with Subqueries
You can combine MAX() with a subquery to filter for rows matching the max value.
SELECT *
FROM employees
WHERE salary = (SELECT MAX(salary) FROM employees);
π― Returns all employees with the highest salary.
π Summary
| Feature | Details |
|---|---|
| Function | MAX() |
| Purpose | Get the highest value in a column |
| Ignores NULLs | β Yes |
| Can be grouped? | β
Yes, with GROUP BY |
| Works with | Numbers, dates, text |