GREATEST()
In SQL Server 2022, the GREATEST() function efficiently retrieves the maximum value from a set of expressions. The syntax is as follows:
–Syntax of the Greatest()
GREATEST ( expression1 [ , …expressionN ] )
Here in this function, we have to give at least one value and after that, we can give as much as values as we want. SQL server will compare them and then the maximum value from them is returned.
If you don’t have SQL Server 2022 then you can also use Azure Data Studio.
Example Usage
So, let’s write a query that returns the maximum from two integers.
SELECT GREATEST(1.2,2,3,4) AS Maximum;
Output:
SQL Server Max Function Takes Two Values Like Math.Max in .NET
In SQL Server 2022, the GREATEST() function simplifies finding the maximum value among a set of parameters. However, for older versions without this function, we explore alternative approaches akin to the Math.Max() function in .NET. This article presents the syntax of GREATEST() and introduces three alternative methods: using a User-Defined Function (UDF), employing the CASE statement, and leveraging the IIF function.