The Use of CASE Statements

Rukayat BalogunRukayat Balogun
1 min read

WHEN: takes the condition you want to evaluate THEN: displays the result of the condition evaluated ELSE: this is the result that gets displayed if the when condition stated are not met END AS: the name of the column that displays the result

SELECT Country, 
       CASE WHEN Country = 'us'  THEN 'USA'
       ELSE 'International'
       END AS SourceCountry
FROM Incidents
-- Complete the syntax for cutting the duration into different cases
SELECT DurationSeconds, 
-- Start with the 2 TSQL keywords, and after the condition a TSQL word and a value
      CASE WHEN (DurationSeconds <= 120) THEN 1
-- The pattern repeats with the same keyword and after the condition the same word and next value          
       WHEN (DurationSeconds > 120 AND DurationSeconds <= 600) THEN 2
-- Use the same syntax here             
       WHEN (DurationSeconds > 601 AND DurationSeconds <= 1200) THEN 3
-- Use the same syntax here               
       WHEN (DurationSeconds > 1201 AND DurationSeconds <= 5000) THEN 4
-- Specify a value      
       ELSE 5 
       END AS SecondGroup   
FROM Incidents
0
Subscribe to my newsletter

Read articles from Rukayat Balogun directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Rukayat Balogun
Rukayat Balogun