WITH starts a common table expression (CTE)
A CTE gives a query result a temporary name so you can reference it in the main query. Here, recent_orders is the CTE's name. The CTE is available only to the SQL statement immediately following it — it is not saved and it is not a temporary table. Once that statement finishes, the name is gone.
A tiny example
In plain English: Give the order list a temporary name, then show me everything in it.
WITH recent_orders AS (
SELECT *
FROM orders
)
SELECT *
FROM recent_orders;What comes back
| id | customer_id | ordered_on |
|---|---|---|
| 101 | 7 | 2024-05-01 |
| 102 | 3 | 2024-05-02 |
The main query read from recent_orders, the CTE's name, and got back the rows the query inside WITH produced.
Related SQL lessons
Ready for a break?
Take on today's cozy puzzle. A fresh, bite-sized query waits every morning — no timers, no pressure.
play today's sip