How to Use a CASE WHEN Statement in SAS (With Examples)?

The CASE WHEN statement in SAS is a powerful and convenient tool used to control the flow of a program by allowing you to apply different conditions to a statement. This statement evaluates an expression and returns a result depending on the condition. It is similar to an IF-THEN-ELSE statement, except with CASE WHEN, you can use multiple conditions and you can specify different results for each condition. Examples of using the CASE WHEN statement are provided for further clarification.


We can use the CASE statement in SAS to create a new variable that uses case-when logic to determine the values to assign to the new variable.

This statement uses the following basic syntax:

proc sql;
    select var1, case
                 when var2 = 'A' then 'North'
               	 when var2 = 'B' then 'South'
               	 when var2 = 'C' then 'East'
                 else 'West'
                 end as variable_name
    from my_data;
quit;

The following example shows how to use the CASE statement in practice.

Example: Using the CASE Statement in SAS

Suppose we have the following dataset in SAS:

/*create dataset*/
data original_data;
    input team $ points rebounds;
    datalines;
A 25 8
A 18 12
A 22 6
B 24 11
B 27 14
C 33 19
C 31 20
D 30 17
D 18 22
;
run;

/*view dataset*/
proc print data=original_data;

We can use the following CASE statement to create a new variable called Division whose values are based on the values of the team variable:

/*create dataset*/
proc sql;
    select team, points, case
                	 when team = 'A' then 'North'
               	         when team = 'B' then 'South'
               	         when team = 'C' then 'East'
                	 else 'West'
                         end as Division
    from original_data;
quit;

case when statement in SAS example

Note that a new variable Division was created whose values are based on the values for the team variable.

The following tutorials explain how to perform other common tasks in SAS:

x