Conditional logic with CASE statements

Data Manipulation in Snowflake

Jake Roach

Field Data Engineer

Using ELSE

$$

Sometimes, there might be additional values that don't fall into a WHEN ... THEN statement.

$$

  • Use ELSE to capture these additional scenarios
  • Great way to catch edge cases
SELECT
    student,
    CASE
        WHEN grade_num = 12 THEN 'Senior'
        WHEN grade_num = 11 THEN 'Junior'
        ...
        ELSE 'Not in HS'  -- Catch others!
    END AS grade
FROM students;
          |   student  |    grade   |
          | ---------- | ---------- |
          |  Viraj     |  Junior    |
          |  Stephanie |  Senior    |
          |  Lewis     |  Not in HS |
Data Manipulation in Snowflake

Evaluating a condition

Operator Condition Example
= Value is equal to another value column_a = 'value_a'
IN (...) Value is in a list of values column_a IN ('value_a', 'value_b')
>, < Value is greater than or less than another value column_a > 0
>=, <= Counterparts to > and <, also includes equality column_a >= 0
BETWEEN Value is between two values, inclusive column_a BETWEEN 0 AND 10

These comparison operators can be combined with AND, OR, or NOT

CASE statements in Snowflake are efficient due to being a column-oriented database

Data Manipulation in Snowflake

Categorizing temperatures

SELECT
    todays_date,
    temperature,
    CASE

WHEN temperature BETWEEN 70 AND 90 THEN 'Ideal for Swimming'
WHEN temperature >= 50 AND tempreature < 70 THEN 'Perfect for Sports'
WHEN temperature > 32 AND temperature < 50 THEN 'Spring/Fall Temps' WHEN temperature > 0 AND temperature <= 32 THEN 'Winter Weather' ELSE 'Extreme Temperatures'
END AS temperature_description FROM weather;
Data Manipulation in Snowflake

Categorizing temperatures

A table with the results of a CASE statement categorizing records by their temperature

Data Manipulation in Snowflake

Combining conditional statements

SELECT
    todays_date,
    temperature,
    status,

CASE WHEN temperature > 70 AND status NOT IN ('Rain', 'Wind') THEN 'Beach'
WHEN temperature BETWEEN 45 AND 70 AND status = 'Sun' THEN 'Sports'
WHEN temperature <= 32 OR status = 'Snow' THEN 'Skiing'
ELSE 'Stay In' END AS activity FROM weather;

We can evaluate multiple columns in a single CASE statement

Data Manipulation in Snowflake

Combining conditional statements

A table with the results of a CASE statement categorizing records by their temperature and outdoor status

Data Manipulation in Snowflake

Let's practice!

Data Manipulation in Snowflake

Preparing Video For Download...