7

Is it possible to return zero if a value is less than zero without using a case statement?

e.g. Max(a, 0) <-- 'Max' doesn't exist.

I would like my code to be as succinct as possible.

10
  • 6
    Why do you not want to use a case expression. This is pretty much what they were made for. Commented Feb 18, 2016 at 15:29
  • 1
    Its in the question! Commented Feb 18, 2016 at 15:36
  • 1
    @Sean he's saying "I do not want to use a case expression" because "I would like my code to be as succinct as possible." Commented Feb 18, 2016 at 17:25
  • 1
    @AaronBertrand I think one gets bonus points for saving characters if the result is not more cryptic. MAX(value, 0) is arguable more clear than CASE WHEN value < 0 THEN 0 ELSE value END. Commented Feb 18, 2016 at 19:02
  • 2
    0 is greater than any negative value. MAX(value, 0) is pretty clear to me. Commented Feb 18, 2016 at 20:20

1 Answer 1

26

Just for fun:

DECLARE @a INT = -3
SELECT COALESCE(NULLIF (ABS(@a), -@a), 0)

This post just hints in the direction that a CASE expression is a much better option to get the expected result.

NULLIF is, after all, just a fancy CASE. The example query above expands (in the execution plan) to:

CASE 
    WHEN 
        CASE 
            WHEN abs([@a])=( -[@a]) 
            THEN NULL 
            ELSE abs([@a]) 
        END IS NOT NULL 
    THEN 
        CASE 
            WHEN abs([@a])=( -[@a]) 
            THEN NULL 
            ELSE abs([@a]) 
        END 
    ELSE (0) 
END

A suitable CASE expression:

-- All versions
SELECT CASE WHEN @a > 0 THEN @a ELSE 0 END;

-- SQL Server 2012 or later
SELECT IIF(@a > 0, @a, 0);
Sign up to request clarification or add additional context in comments.

2 Comments

@PaulWhite: so another reason to use this simple version: SELECT CASE WHEN @a < 0 THEN 0 ELSE @a END
An alternative expression that handles NULLs: @A * ( ( Sign( @A ) + 1 ) / 2 )

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.