Chain multiple named steps in one query.

Section: Common Table Expressions

Multiple CTEs

sql
sql
WITH order_totals AS (
  SELECT customer_id, SUM(amount) AS total_spent
  FROM orders
  GROUP BY customer_id
),
ranked AS (
  SELECT customer_id, total_spent
  FROM order_totals
)
SELECT *
FROM ranked;
Explanation

Multiple CTEs are useful for staged transformations.

Learn the surrounding workflow

Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.

Related commands

Same sheet · prioritizing Common Table Expressions
Basic CTE
Create a named subquery for readability and reuse.
OpenIn sheetsqlsame section
Recursive CTE
Traverse hierarchical or graph-like data.
OpenIn sheetsqlsame section
Assign row numbers
Number rows within an ordered partition.
Use LAG
Read a value from the previous row in the same partition.
Bucket rows with NTILE
Divide ordered rows into a fixed number of groups.
Rank rows
Assign ordered rankings with or without gaps.