Create a named subquery for readability and reuse.

Section: Common Table Expressions

Basic CTE

sql
sql
WITH recent_orders AS (
  SELECT *
  FROM orders
  WHERE created_at >= CURRENT_DATE - INTERVAL "30 days"
)
SELECT customer_id, COUNT(*) AS total_recent_orders
FROM recent_orders
GROUP BY customer_id;
Explanation

CTEs make multi-step queries easier to read and maintain.

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
Multiple CTEs
Chain multiple named steps in one query.
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.