T-SQL – Select Max or Min value from a list of values

If you need to select max or min value from a list of values, you can use the code below. Advantage of this code snippet is that it doesn’t use any temp tables or user defined functions, and it also works if one or more values are NULL.

SELECT MAX(n)
FROM (VALUES (12), (4), (5), (19), (2), (21), (0), (NULL)) AS i(n)

Returned result will be 21.

SELECT MIN(n)
FROM (VALUES (12), (4), (5), (19), (2), (21), (0), (NULL)) AS i(n)

Returned result will be 0.

You can use variables in place of hard coded values above. All variables used must be of the same type. Variables can contain null values.

SELECT MAX(n)
FROM (VALUES (@MyVar1), (@MyVar2), (@MyVar3), (@MyVar4)) AS i(n)
SELECT MIN(n)
FROM (VALUES (@MyVar1), (@MyVar2), (@MyVar3), (@MyVar4)) AS i(n)
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s