Shorthand CASE in SELECT

suggest change

CASE’s shorthand variant evaluates an expression (usually a column) against a series of values. This variant is a bit shorter, and saves repeating the evaluated expression over and over again. The ELSE clause can still be used, though:

SELECT Id, ItemId, Price,
  CASE Price WHEN 5  THEN 'CHEAP'
             WHEN 15 THEN 'AFFORDABLE'
             ELSE         'EXPENSIVE'
  END as PriceRating
FROM ItemSales

A word of caution. The shorthand form evaluates its input expression once, then compares that result to each WHEN value. NEWID() and CHECKSUM below are SQL Server functions. The following statement therefore uses one random value for every comparison:

SELECT 
    CASE ABS(CHECKSUM(NEWID())) % 4
        WHEN 0 THEN 'Dr'
        WHEN 1 THEN 'Master'
        WHEN 2 THEN 'Mr'
        WHEN 3 THEN 'Mrs'
    END

returns one of the four titles. It is not equivalent to a searched CASE that calls NEWID() again in every WHEN:

SELECT 
    CASE 
        WHEN ABS(CHECKSUM(NEWID())) % 4 = 0 THEN 'Dr'
        WHEN ABS(CHECKSUM(NEWID())) % 4 = 1 THEN 'Master'
        WHEN ABS(CHECKSUM(NEWID())) % 4 = 2 THEN 'Mr'
        WHEN ABS(CHECKSUM(NEWID())) % 4 = 3 THEN 'Mrs'
    END

That searched form can miss every WHEN and return NULL.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents