Search code examples
sqlsql-server-2014

CROSS APPLY for CASE expressions


Is there any value in using a CROSS APPLY to encapsulate CASE expression(s). Let me explain the question with an example.

Data Setup

DECLARE @data AS TABLE([id] INT IDENTITY(1,1), [value] BIGINT);
INSERT INTO @data([value])
VALUES (100), (200), (7), (128), (315);

Query #1

The following query uses a traditional pattern of CASE expressions in the SELECT statement.

SELECT [id]
, [value]
, CASE WHEN [value] < 100 THEN 'CLASS-C'
    WHEN [value] < 200 THEN 'CLASS-B'
    ELSE 'CLASS-A' END AS [rating]
FROM @data

Query #2

Encapsulates the CASE expression in an APPLY

SELECT [id]
, [value]
, [rating]
FROM @data
CROSS APPLY(SELECT CASE WHEN [value] < 100 THEN 'CLASS-C'
    WHEN [value] < 200 THEN 'CLASS-B'
    ELSE 'CLASS-A' END AS [rating]) AS [applied]

Basic Analysis

Results of both queries are the same and the execution plan is also similar.


Solution

  • You can refer rating multiple times in the SELECT, WHERE, GROUP BY, or later in the FROM clause.

    This is a convenient way to define columns referred to multiple times.