Sql Server Min Function

SQL Server: MIN Function

In this post explains how to use the MIN function in SQL Server (Transact-SQL) with syntax and examples.

Description

In SQL Server (Transact-SQL), the MIN function returns the minimum value of an expression.

Syntax

The syntax for the MIN function in SQL Server (Transact-SQL) is:

SELECT MIN(aggregate_expression)
FROM tables
[WHERE conditions];

OR the syntax for the MIN function when grouping the results by one or more columns is:

SELECT expression1, expression2, ... expression_n,
       MIN(aggregate_expression)
FROM tables
[WHERE conditions]
GROUP BY expression1, expression2, ... expression_n;

Parameters or Arguments

expression1, expression2, ... expression_n

Expressions that are not encapsulated within the MIN function and must be included in the GROUP BY clause at the end of the SQL statement.

aggregate_expression

This is the column or expression from which the minimum value will be returned.

tables

The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause.

WHERE conditions

Optional. These are conditions that must be met for the records to be selected.

Applies To

The MIN function can be used in the following versions of SQL Server (Transact-SQL):

  • SQL Server 2017, SQL Server 2016, SQL Server 2014, SQL Server 2012, SQL Server 2008 R2, SQL Server 2008, SQL Server 2005

Example - With Single Field

Let's look at some SQL Server MIN function examples and explore how to use the MIN function in SQL Server (Transact-SQL).

For example, you might wish to know how the minimum quantity of all products.

SELECT MIN(quantity) AS "Lowest Quantity"
FROM products;

In this MIN function example, we've aliased the MIN(quantity) expression as "Lowest Quantity". As a result, "Lowest Quantity" will display as the field name when the result set is returned.

Example - Using GROUP BY

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

For example, you could also use the MIN function to return the product_type and the minimum quantity for that product_type.

SELECT product_type, MIN(quantity) AS "Lowest Quantity"
FROM products
GROUP BY product_type;

Because you have listed one column in your SELECT statement that is not encapsulated in the MIN function, you must use a GROUP BY clause. The department field must, therefore, be listed in the GROUP BY section.