MIN and MAX

Beginner

In SQL, the MIN() and MAX() functions are aggregate functions used to find the smallest and largest values in a specified column, respectively. These functions are useful for retrieving summary information about numerical or date/time data in a table.

Basic syntax

The MIN() function returns the smallest value in a specified column.

SELECT MIN(column_name)
FROM table_name
WHERE condition
  • MIN(column_name): This returns the smallest value in the specified column_name.
  • table_name: This is the name of the table from which you want to retrieve the data.
  • condition: This is an optional condition that specifies which rows to include in the calculation.

The MAX() function returns the largest value in a specified column.

SELECT MAX(column_name)
FROM table_name
WHERE condition
  • MAX(column_name): This returns the largest value in the specified column_name.
  • table_name: This is the name of the table from which you want to retrieve the data.
  • condition: This is an optional condition that specifies which rows to include in the calculation.

Examples

  1. Finding the Minimum and Maximum Salaries

Consider a table named employees with a salary column. To find the minimum and maximum salaries of all employees, you can use:

SELECT MIN(salary) AS min_salary, MAX(salary) AS max_salary
FROM employees

This query will return the smallest and largest salaries among all employees.

  1. Finding the Minimum and Maximum Dates

Suppose you have a table named orders with an order_date column. To find the earliest and latest order dates, you can use:

SELECT MIN(order_date) AS earliest_date, MAX(order_date) AS latest_date
FROM orders

This query will return the earliest and latest dates among all orders.

Additional notes

  • The MIN() and MAX() functions can be used with various data types, such as numeric, string, date, and time types, depending on the column they are applied to.
  • If the specified column contains NULL values, the MIN() and MAX() functions will ignore them and return the minimum or maximum value from the non-NULL values.