Common table expression (CTE)

Applies to: sql

A CTE is a named temporary result defined with WITH, used to break a complex query into readable, composable steps. It reads top to bottom like a pipeline and can be referenced multiple times.

WITH active AS (
  SELECT user_id FROM events WHERE ts > NOW() - INTERVAL '7 days'
)
SELECT COUNT(*) FROM active;

See also: select, window-function