How to Write a Common Table Expression in PostgreSQL

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 (
  select *
  from users
  where beta is true

select events.*
from events
inner join beta_users on = events.user_id

You can find a real world example of a CTE in How to Calculate Cumulative Sum/Running Total in PostgreSQL.

Better SQL for the people
Get more done with PopSQL and PostgreSQL