Monday, April 21, 2014

TSQL Tutorial: MIN Function

The TSQL MIN function is used to return the minimum value of an expression in a SELECT statement.
The syntax for the TSQL MIN function is:

SELECT MIN(expression)
FROM tables
WHERE conditions;

The most simple ways to see example is to get minimum value for a particular column. In below example its Employee table which has Salary column and we want min value in this column.

SELECT MIN(salary) AS "Lowest salary"
FROM employees;


In some cases, you will be required to use the TSQL GROUP BY clause with the TSQL MIN function.

For example, you could also use the TSQL 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 TSQL SELECT statement that is not encapsulated in the TSQL MIN function, you must use the TSQL GROUP BY clause. The department field must, therefore, be listed in the GROUP BY section.

No comments:

Post a Comment