The SQL MIN Function is one of the Aggregate Function, which is used to find the Minimum value from the total records (or rows) selected by the SELECT Statement. The SQL Server MIN Function will ignore Null values.
SQL Min Function Syntax
The basic syntax of the MIN Function In SQL Server is as shown below:
SELECT MIN ([Column_Name]) FROM [Source]
In this article we will show you, How to write SQL Server Min Function with example. For this, We are going to use the below shown data
SQL MIN Example
The Min function in SQL Server simply returns the Minimum value from the total records present in the specified column.
For example, The following query will find the Minimum yearly income present in the [Yearly Income] column from Customers table.
-- SQL Server MIN Function example SELECT MIN ([YearlyIncome]) AS [Minimum Income] FROM [Customer]
SQL MIN Group By Clause
In most cases we usually check minimum product price (Lowest pricing product) belongs to particular category or color etc.
In these situations we use GROUP BY Clause to group the products by color or category and then use the SQL Min Function to find the Lowest pricing product present in each group. Let us see the Example
-- SQL Server MIN Function example SELECT [Occupation] ,MIN ([YearlyIncome]) AS [Minimum Income] FROM [Customer] GROUP BY [Occupation]
Above Query will find, the Customers associated with the particular Department and finds the minimum income of a customer present in each department
SQL MIN Having Clause
When we are grouping the data, In some cases we usually check for the conditions against the aggregated data. In these situations we use HAVING Clause along with Group By Statement.
For example, The following sql server min function query will group the Customers by their Occupation and then finds the Minimum yearly Income present in each group.
-- SQL Server MIN Function example SELECT [Occupation] ,MIN ([YearlyIncome]) AS [Minimum Income] FROM [Customer] GROUP BY [Occupation] HAVING MIN ([YearlyIncome]) > 50000
Below lines of code will check whether the aggregated amount (Minimum Yearly income of each individual Group) is greater than 50000 or not. If this is True then corresponding records will be displayed.
HAVING MIN ([YearlyIncome]) > 50000
SQL Min Subquery
For example, The following Sql Server min function query will return all the Customers present in the customers table whose [Yearly Income] is greater than the Minimum yearly income.
-- SQL Server MIN Function example SELECT [FirstName] ,[LastName] ,[YearlyIncome] ,[Education] ,[Occupation] FROM [Customer] WHERE [YearlyIncome] > (SELECT MIN([YearlyIncome]) FROM [Customer])
From the first Sql Server min function example you can observe that, Minimum Yearly Income is 50000. So above query will display all the customers from the Customers table whose yearly income is greater than 50000
Thank You for Visiting Our Blog