Friday, December 20, 2024

MySQL MAX() Function

 The MAX() function in MySQL is used to return the maximum value from a specified column. It is commonly used with numerical, date, or string data types to find the largest value within a set of rows.

Syntax:

SELECT MAX(column_name) 
FROM table_name 
[WHERE condition];

Key Points:

  1. Aggregate Function: MAX() is an aggregate function, meaning it operates on a set of values and returns a single value.
  2. NULL Values: It ignores NULL values while determining the maximum value.
  3. Grouping: You can use it with the GROUP BY clause to find the maximum value for each group of data.

Examples:

1. Find the Maximum Value in a Column:

SELECT MAX(salary) AS highest_salary
FROM employees;

This query retrieves the highest salary from the employees table.


2. Use with a Condition:

SELECT MAX(salary) AS highest_salary
FROM employees
WHERE department = 'IT';

This retrieves the highest salary for employees in the IT department.


3. Use with GROUP BY:

SELECT department, MAX(salary) AS highest_salary
FROM employees
GROUP BY department;

This returns the highest salary in each department.


4. Use with Date Values:

SELECT MAX(joining_date) AS latest_joining_date
FROM employees;

This retrieves the most recent joining date from the employees table.


5. Use with Strings:

When applied to string columns, MAX() returns the string with the highest alphabetical order.

SELECT MAX(employee_name) AS last_name
FROM employees;

Let me know if you'd like more examples or clarification!

No comments:

Post a Comment