MySQL MIN() function


The MIN() function in MySQL is an aggregate function used to retrieve the minimum value from a column. It is useful for finding the lowest value in a dataset, such as the minimum salary, the earliest date, or the smallest quantity. The function can operate on numeric, date, and time data types.

Syntax

MIN(column_name)
  • column_name: The name of the column from which to retrieve the minimum value.

Usage

  1. Basic Minimum Value Retrieval

    To find the lowest value in a numeric column:

    SELECT MIN(salary) AS lowest_salary FROM employees;

    This query retrieves the minimum salary from the employees table and labels it as lowest_salary.

  2. Minimum with Conditions

    To find the minimum value based on specific conditions, use the WHERE clause:

    SELECT MIN(amount) AS min_sales FROM sales WHERE status = 'Completed';

    This query retrieves the minimum sales amount where the status is 'Completed'.

  3. Minimum with Grouping

    To find the minimum value for each group of rows, use the GROUP BY clause:

    SELECT department, MIN(salary) AS lowest_salary FROM employees GROUP BY department;

    This query retrieves the minimum salary within each department.

  4. Minimum with HAVING Clause

    To filter groups based on the minimum value, use the HAVING clause:

    SELECT department, MIN(salary) AS lowest_salary FROM employees GROUP BY department HAVING MIN(salary) < 30000;

    This query retrieves departments where the minimum salary is less than 30,000.

  5. Minimum for Non-Numeric Data

    The MIN() function can also be used with date and time columns:

    SELECT MIN(order_date) AS earliest_order FROM orders;

    This query retrieves the earliest order date from the orders table.

  6. Handling NULL Values

    The MIN() function ignores NULL values in the specified column. If a column contains NULL values, they are not included in the minimum value calculation:

    SELECT MIN(bonus) AS min_bonus FROM employees;

    If some bonus values are NULL, they are excluded from the minimum calculation.