Applying conditional logic in Snowflake

Data Manipulation in Snowflake

Jake Roach

Field Data Engineer

Aggregation with CASE statements

Queries with a CASE statement can still use aggregation functions.

  • SUM()
  • AVG()
  • MIN()
  • MAX()
  • ...
  • MODE()

$$

Just make sure to include a GROUP BY!

A skeleton of a CASE statement that includes aggregation and grouping

Data Manipulation in Snowflake

Aggregation with CASE statements

SELECT
    CASE
        WHEN month_num IN (12, 1, 2) THEN 'Winter'
        WHEN month_num IN (3, 4, 5) THEN 'Spring'
        WHEN month_num in (6, 7, 8) THEN 'Summer'
        ELSE 'Fall'
    END AS season,

AVG(temperature) AS average_temperature, -- Manipulate data with AVG()
year_num FROM weather GROUP BY season, year_num; -- Remember to group by non-aggregated fields
Data Manipulation in Snowflake

Aggregation with CASE statements

Results of a query that finds the average temperature for each season and year

Data Manipulation in Snowflake

Aggregating CASE'd fields

SELECT
    season,
    AVG(
        CASE
            WHEN season = 'Winter' THEN temperature - 30
            WHEN season IN ('Spring', 'Fall') THEN temperature - 60
            WHEN season = 'Summer' THEN temperature - 75
        END
    ) AS relation_to_average_temperature
FROM weather
GROUP BY season;
Data Manipulation in Snowflake

Aggregating CASE'd fields

Table displaying the relation of average temperature by season

Data Manipulation in Snowflake

JOIN's

SELECT
    ...

    -- Define a CASE statement
    CASE ...

FROM <left_table>

-- JOIN new records to existing table
LEFT JOIN <right_table> 
    ... 
;

CASE statements can be constructed using data joined from two different tables.

  • Use columns from more than one table in a CASE statement
  • LEFT, RIGHT, INNER, OUTER, etc.
  • Combine with other tools, including aggregation functions

$$

$$

                                          Let's check it out!

Data Manipulation in Snowflake

Determining college credit status

SELECT
    students.student_name,
    student_courses.course_name,

-- Evaluate both the student's grade number and grade for the course CASE WHEN students.grade_num = 12 AND student_courses.grade > 90 THEN 'College Credit Eligible' ELSE 'Too Early for College Credit' END AS college_credit_status
FROM student_courses LEFT JOIN students ON student_courses.student_id = students.student_id;
Data Manipulation in Snowflake

Determining college credit status

The results of a query against a the JOINED students and student_courses table

Data Manipulation in Snowflake

Let's practice!

Data Manipulation in Snowflake

Preparing Video For Download...