Advanced Common Table Expressions

Data Manipulation in Snowflake

Jake Roach

Field Data Engineer

Defining multiple Common Table Expressions

More than one common table expression can be defined using a single WITH clause

$$

  • Arbitrary # of CTE's can be defined
  • CTE's can be JOIN'd together
  • Can still perform complex operations in a CTE
  • Could even use the results of one CTE in another
WITH <cte-name> AS (

    <query>

), <another-cte-name> (

    -- Add another query!
    <another-query>
)

-- These CTE's could be JOIN'd 
SELECT ... ;
Data Manipulation in Snowflake

Top-performing courses

WITH active_courses AS (
    SELECT
        id,
        course_name,
        teacher_name
    FROM courses
    WHERE is_active

), course_avgs ( SELECT course_id, AVG(grade) AS avg_grade FROM student_courses GROUP BY course_id )

SELECT
    a.course_name,
    a.teacher_name,
    c.avg_grade
FROM active_courses AS a

-- JOIN these CTEs together
JOIN course_avgs AS c
    ON a.id = c.course_id

ORDER BY avg_grade DESC;

Query becomes easier to understand!

Data Manipulation in Snowflake

Top-performing courses

The temporary result sets combining to form the final output of average scores and teacher names for each course

Data Manipulation in Snowflake

Tenured teachers

WITH active_courses AS (
    SELECT
        id,
        course_name,
        teacher_name,
        teacher_tenure
    FROM courses

    -- JOIN the teachers table to the courses 
    -- table to get teacher_tenure
    JOIN teachers 
        ON courses.teacher_id = teachers.id

    WHERE is_active
), 
...
...
), course_avgs (
    SELECT
        course_id,
        AVG(grade) AS avg_grade
    FROM student_courses
    GROUP BY course_id
)

SELECT a.teacher_name, a.teacher_tenure MAX(c.avg_grade) AS highest_grade FROM active_courses AS a JOIN course_avgs AS c ON a.id = c.course_id GROUP BY a.teacher_name, a.teacher_tenure;
Data Manipulation in Snowflake

Tenured teachers

Result set of a query to find teacher tenure and their highest course average

Data Manipulation in Snowflake

Let's practice!

Data Manipulation in Snowflake

Preparing Video For Download...