SQL MIN Function
The SQL MIN()
is an aggregate function used to find the minimum value or the lowest value of a column or expression.
Syntax
The basic syntax for the MIN
function is as follows:
SELECT MIN(column_name)
FROM table_name
WHERE condition;
Or the syntax for the MIN
function when used with the GROUP BY clause:
SELECT colunm1_name, column2_name, ... columnN_name, MIN(column_name)
FROM table_name
WHERE condition
GROUP BY column1_name, column2_name, ... columnN_name
Parameters:
colunm1_name, column2_name, ... columnN_name
: Column that are not encapsulated within the MIN function and must be included in theGROUP BY
caluse.column_name
: This is the column from which the MIN function will be returned.
Demo table
Let us suppose that we have a table called "Employee" with the following data:
emp_no | name | birth_date | hire_date | salary | dept_name |
---|---|---|---|---|---|
1001 | James Smith | 1991-10-23 | 2010-05-13 | 6600 | Customer Service |
1002 | Maria Martinez | 1993-06-13 | 2018-10-08 | 9000 | Development |
1003 | Andrew Rodriguez | 1994-10-25 | 2019-01-23 | 9500 | Finance |
1004 | Robert Hernandez | 1995-09-07 | 2019-09-08 | 9600 | Development |
1005 | Donna Williams | 1996-03-15 | 2012-06-06 | 7400 | Finance |
1006 | James Johnson | 2001-04-30 | 2014-02-18 | 8000 | Marketing |
1007 | Stephanie Miller | 1998-01-17 | 2009-12-12 | 8500 | Human Resources |
1008 | Nelson Lopez | 1999-05-26 | 2010-10-06 | 7300 | Marketing |
SQL MIN Function With Single Expression Example
The primary way to use the MIN()
function is to return as a single field that calculates the MIN
value.
The following SQL statement will return the minimum salary of all employees in the table "Employee".
SELECT MIN(salary) AS 'Min Salary'
FROM employee;
Here we used an sql alias for the MIN(salary) field as "Min Salary".
The above SQL statement will output the following result set:
+------------+ | Min Salary | +------------+ | 6600 | +------------+
SQL MIN Function Using SQL GROUP BY Example
In some real-life situations, you will need to use the MIN
function with the GROUP BY clause.
The following SQL statement will output the name of each department and the minimum salary for the department.
SELECT dept_name AS 'department', MIN(salary) AS 'Min Salary'
FROM employee
GROUP BY dept_name;
The above SQL statement will output the following result set:
+------------------+------------+ | Department | Min Salary | +------------------+------------+ | Customer Service | 6600 | | Development | 9000 | | Finance | 7400 | | Human Resources | 8500 | | Marketing | 7300 | +------------------+------------+
Note: Every column that is listed in the SELECT statement and not encapsulated in the SQL aggregation functions (HERE is the MIN function) must be used in the GROUP BY clause.