How do I use a CTE to make a multi-step SELECT easier to read?
Quick answer
Put the aggregation in a named CTE after WITH, then query that CTE in the following SELECT. For example, calculate each customer’s order total in totals, then keep rows where total > 100. This separates the calculation from the filter and can make the query easier to follow. In SQLite, an ordinary CTE is a temporary, view-like definition for one SQL statement; it is not necessarily materialized. [S1]
The question, the details, the next step.
A practical checklist
Name the intermediate result with a CTE that describes what it contains, such as
totals.Select the grouping column and aggregate the intended value in the CTE.
Group by the identifier that defines each result row.
Read from the CTE in the following SELECT and apply the intended threshold.
Check whether the boundary should use
>or>=before running the query.
A few more useful answers
Does a CTE always make a query faster?
This example uses a CTE to name an intermediate calculation and improve readability. The cited SQLite guidance does not establish that a CTE is necessarily materialized or that it improves runtime. [S1]
Can I define more than one CTE?
SQLite allows a WITH clause to define one or more CTEs before the main SELECT. [S1] This example needs only one intermediate result.
Does this example include customers with no orders?
No. It groups rows in orders, so customers with no order rows are not included. Including every customer would require a different query shape.
Sources
References used for this guide.
- [S1] SQLite The WITH Clause: Ordinary Common Table Expressions sqlite.org · Checked
