A derived table puts a step in the middle of the query. WITH puts it at the top, with a name:
sql
WITH max_budget AS (
SELECT MAX(budget) AS value
FROM department
)
SELECT d.dept_name, d.budget
FROM department d, max_budget m
WHERE d.budget = m.value;WITH max_budget ASname( SELECT MAX(budget) AS value FROM department )its querySELECT … FROM department d, max_budget m …the statement that uses it
- The named query is a common table expression (CTE).
- The statement below
WITHuses the name like a table: inFROM, in a join, in a subquery. - The CTE exists only for this one statement.
Several steps
Separate CTEs with commas. A later CTE can use an earlier one, and the final query can use each of them more than once:
text
WITH step_one AS (…),
step_two AS (SELECT … FROM step_one …)
SELECT … FROM step_two …;The query reads from top to bottom, one step at a time. Use WITH when a query has more than one level.