Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return zero if value less than zero [duplicate]

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.

like image 213
Ian Warburton Avatar asked Jul 11 '26 05:07

Ian Warburton


1 Answers

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);
like image 52
Giorgos Betsos Avatar answered Jul 18 '26 07:07

Giorgos Betsos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!