SQL WITH: named queries and statement scope
Overview
A common table expression (CTE) names a query result for use within a single SQL statement. WITH separates a useful intermediate result from the final SELECT without creating a permanent table.
First example
WITH affordable AS ( SELECT id, name FROM products WHERE price_cents < 500)SELECT id, name FROM affordable ORDER BY id;Observed SQLite result (rows in JSON):
[ [ 1, "Notebook" ], [ 2, "Pen" ], [ 4, "Pencil" ]]How it works
Write WITH name AS (query), then refer to name in FROM. The first example selects affordable products; the second names two output columns explicitly and calculates total units per product. Unlike a view created with CREATE VIEW, the name does not survive the statement. A derived table in FROM serves a similar purpose but does not provide a named result reusable throughout the statement. Neither construct promises physical storage. Explicitly sort the final SELECT.
Practical example
WITH units(product_id, total_units) AS ( SELECT product_id, SUM(quantity) FROM order_items GROUP BY product_id)SELECT product_id, total_units FROM units ORDER BY product_id;Observed SQLite result (rows in JSON):
[ [ 1, 2 ], [ 2, 7 ], [ 3, 1 ]]Practice and mistakes
Practice: change the threshold to 200 cents (IDs 2 and 4). Run the first statement, then separately try SELECT from affordable: the name is no longer available. A CTE is not a session-scoped temporary table.