SQL Server MIN

In the realm of database management, SQL Server offers a plethora of functions to simplify data manipulation and retrieval. One such essential function is the MIN() function. It is a fundamental tool for anyone working with databases, as it helps extract the smallest value from a dataset. In this blog, we’ll dive deep into the SQL Server MIN() function, exploring its syntax, usage, and practical examples.

The MIN function in SQL Server is an aggregate function that returns the smallest (minimum) value from a specified column or expression. It is commonly used to find the lowest value in a dataset and works with numerical, date/time, and string data types. The MIN function ignores NULL values. The MIN() function operates on a column of data and can be used in conjunction with other SQL clauses, such as GROUP BY or WHERE, to narrow down the scope of the query.

Syntax

MIN ( [ ALL ] expression )

expression: The column or calculated value for which the minimum value is sought. This can include columns, constants, or expressions.

ALL: This is the default and indicates that all values will be considered.

Key Points

The MIN function is often used with the GROUP BY clause to calculate the minimum value for groups of data.
It does not include NULL values when determining the minimum.
It can be used with numeric, date/time, and string types. For strings, the function returns the value that appears first in alphabetical order.

Examples

1. Find the minimum value in a column

SELECT MIN(Salary) AS MinSalary
FROM Employees;

This query returns the lowest salary from the Employees table.

2. Find the minimum value for each group

SELECT DepartmentID, MIN(Salary) AS MinSalary
FROM Employees
GROUP BY DepartmentID;

This query finds the minimum salary for each department.

3. Using MIN with date/time values

SELECT MIN(HireDate) AS EarliestHireDate
FROM Employees;

This query returns the earliest hire date in the Employees table.

4. Using MIN with string values

SELECT MIN(FirstName) AS FirstAlphabeticalName
FROM Employees;

This query returns the first name that appears alphabetically in the FirstName column.

Important Notes

When used without GROUP BY, the MIN function considers the entire dataset.
When used with GROUP BY, it calculates the minimum for each group defined by the grouping column(s).
If the column contains only NULL values, the result will also be NULL.

The MIN function is a powerful tool for summarizing data and identifying key values, such as the smallest numbers, earliest dates, or lowest alphabetical order.