Friday, December 20, 2024

MySQL MIN() Function

 The MIN() function in MySQL is an aggregate function that returns the smallest value in a specified column. It is commonly used to find the minimum value in a set of rows, typically within a GROUP BY query or across the entire table.

Syntax

SELECT MIN(column_name)
FROM table_name
WHERE condition;

Key Points

  1. Works with Numeric, Date, and String Columns:

    • For numeric columns, it returns the smallest numeric value.
    • For date columns, it returns the earliest date.
    • For string columns, it returns the alphabetically first value.
  2. Ignores NULL Values:

    • The MIN() function skips NULL values in the column.
  3. Can Be Used with GROUP BY:

    • You can use MIN() with GROUP BY to find the minimum value for each group.

Examples

1. Find the Smallest Numeric Value

SELECT MIN(salary) AS MinSalary
FROM employees;

2. Find the Earliest Date

SELECT MIN(hire_date) AS EarliestHireDate
FROM employees;

3. Use with GROUP BY

SELECT department_id, MIN(salary) AS MinSalary
FROM employees
GROUP BY department_id;

4. Find the Alphabetically First Value

SELECT MIN(first_name) AS FirstName
FROM employees;

Practical Considerations

  • Combine MIN() with other aggregate functions (like MAX()) for a complete statistical analysis.
  • Use the WHERE clause to filter rows before applying MIN().

Would you like an example dataset or more advanced usage of the MIN() function?

No comments:

Post a Comment