SQL Server Case Expression


CASE is SQLs answer to other programming languages IF-ELSE statement. If you need to test a condition and return a value CASE is the expression you need.


Introduction
Syntax
CASE with one condition
CASE with multiple conditions
Limitations and Gotchas


Introduction

In this example, I’m going to load a subset of the top-selling Sega Genesis games dataset into SQL Server.

sql server case expression


Syntax

  • Each ‘WHEN’ line tests to see if a condition has been met, if it has it returns the ‘RESULT’, if not it moves on to check the next condition.
  • If none of the specified conditions is met it returns what we specify after ‘ELSE’.
  • Every CASE expression needs to finish with ‘END’.
  • An optional extra is to add a column name to our result.

This makes a lot more sense with examples, so lets get started with our Sega Genesis dataset.


CASE with one condition

In our first example we are using CASE to test one condition. We want to create a new column that shows if a game is from the Sonic series or not.

  • When the game name contains the string ‘Sonic’ the expression returns ‘Y’, if not it returns ‘N’.
  • The last step is to create the column name ‘Sonic Series’

sql server case expression


CASE with multiple conditions

In this example we are using CASE to test multiple conditions. We want to create a new column that shows if Global sales are low, mid or high.

  • When the games Global sales are greater than or equal to 4.00 the expression returns ‘high’, if not it moves on to the next step.
  • If the games Global sales are less than or equal to 3.99 and greater than 2.00 the expression returns ‘mid’.
  • If the games Global sales do not meet either of these conditions the expression returns ‘low’.
  • The last step is to create the column name ‘Sales Range’

 

sql server case expression


Limitations and Gotchas

The CASE Expression is powerful and makes evaluating conditions simple. However, there are some limitations to be aware of:

  • In SQL Server there can only be up to 10 levels of nesting.
  • CASE Expressions cannot check for NULLs.
  • The expression works sequentially in the order specified so when a condition is satisfied it will stop.

Having said that the CASE expression is flexible and can be used in ORDER BY, views, in aggregates with HAVING and to UPDATE data. If you need to perform IF-ELSE conditions in SQL, give it a try.


 

Photo by Nidhi Tokas Dahiya from Pexels

Bitnami