Is there a Max function in SQL Server that takes two values like Math.Max in .NET?
Harness the power of the CASE
statement in SQL Server to mimic the functionality of Math.Max
in .NET: it selects the greater of the two values, valueA and valueB, on a per-row basis in YourTable. This concise code gives you the maximum value under the alias MaxValue.
Dealing with multiple values
In situations where two values simply don't cut it and you're dealing with multiple variables, fear not. SQL Server has got you covered. Use a VALUES
subquery in combination with CROSS APPLY
to deliver a Math.Max-like function across multiple columns:
This unpivot-like function lets MAX
do its thing, and finds the highest value per row across multiple columns. In short: MAX
on steroids.
Alternative methods to get the max value
Using IIF for Clear-cut Cases
If you're lucky enough to be on SQL Server 2012 or later, let IIF
be your friend. It’s a quick and dirty way to get the max of two values:
But beware the null monster: IIF
views any comparison involving NULL
as non-existent.
Playing safe with NULLs
Nulls are like quantum particles, they act in strange ways. To avoid unexpected results, be null-safe with ISNULL
or COALESCE
:
Creative use of Aggregate Functions
The Jack of all trades masterstroke: a single line of code that finds the maximum of values within a single row, rather than an entire column:
Sure, it's a bit left field. But it saves a complete row scan, making your DBA nod approvingly.
Larger values and bespoke requirements handling
When it comes to super sized numbers and needs as custom as your grandma's secret apple pie recipe, here’s what SQL Server offers:
Taking large numbers into account
Don't let the fear of overflow choke your operations. Keep it cool with a BIGINT
cast:
Custom User-defined Functions for frequent use
If you're finding yourself reaching for the Math.Max
stars often, why not create a bespoke dbo.InlineMax
UDF?
Invoke it directly in your SELECT
queries to seamlessly get the maximum value:
Showcasing clarity
Never forget, clarity is key. Tailor your table and column names for everyone's sanity.
Was this article helpful?