📘Introducing SQL Notebooks: Tell stories using data.Read more →

How to Write a Common Table Expression in Snowflake in Snowflake

Common table expressions (CTEs) are a great way to break up complex queries. Snowflake also supports this functionality. Here's a simple query to illustrate how to write a CTE:

with free_users as (
  select *
  from users
  where plan = 'free'
select user_sessions.*
from user_sessions
inner join free_users on free_users.id = user_sessions.user_id
order by free_users.id;

You can find more complex examples of using CTE's in How to Avoid Gaps in Data in Snowflake and in Calculating Cumulative Sums in Snowflake.

Ready for a modern SQL editor?