Data Manipulation in Snowflake
Jake Roach
Field Data Engineer
More than one common table expression can be defined using a single WITH
clause
$$
JOIN
'd togetherWITH <cte-name> AS (
<query>
), <another-cte-name> (
-- Add another query!
<another-query>
)
-- These CTE's could be JOIN'd
SELECT ... ;
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!
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