Wednesday, January 9, 2013

MIN Function


The SQL MIN function returns the minimum value of an expression.
The syntax for the SQL MIN function is:
SELECT MIN(expression )
FROM tables
WHERE predicates;

SQL MIN Function - Single field example

The simplest way to use the SQL MIN function would be to return a single field that calculates the MIN value.
For example, you might wish to know the minimum salary of all employees.
SELECT MIN(salary) as "Lowest salary"
FROM employees;
In this SQL MIN function example, we've aliased the min(salary) field as "Lowest salary". As a result, "Lowest salary" will display as the field name when the result set is returned.

SQL MIN Function - Using SQL GROUP BY Clause example

In some cases, you will be required to use the SQL GROUP BY clause with the SQL MIN function.
For example, you could also use the SQL MIN function to return the name of each department and the minimum salary in the department.
SELECT department, MIN(salary) as "Lowest salary"
FROM employees
GROUP BY department;
Because you have listed one column in your SQL SELECT statement that is not encapsulated in the SQL MIN function, you must use the SQL GROUP BY clause. The department field must, therefore, be listed in the GROUP BY section.