Common table expressions (CTEs) are a great way to break up complex PostgreSQL queries. Here's a simple query to illustrate how to write a CTE:
with beta_users as (
where beta is true
inner join beta_users on beta_users.id = events.user_id
You can find a real world example of a CTE in How to Calculate Cumulative Sum/Running Total in PostgreSQL.
Spread the word