Multiple CTEs with Dependency
Multiple CTEs with Dependency is a SQL statement in the CTE (WITH) category. CTEs can reference previous CTEs in the same WITH clause, creating a chain of transformations. The syntax is WITH cte1 AS (...), cte2 AS (SELECT ... FROM cte1) SELECT * FROM cte2;. It returns chained CTE result. A typical example: WITH sales_2024 AS ( SELECT product_id, SUM(amount) AS total_sales FROM orders WHERE YEAR(order_date) = 2024 GROUP BY product_id ), top_products AS ( SELECT product_id, total_sales FROM sales_2024 ORDER BY total_sales DESC LIMIT 10 ), product_names AS ( SELECT tp.product_id, tp.total_sales, p.name FROM top_products tp JOIN products p ON tp.product_id = p.id ) SELECT * FROM product_names ORDER BY total_sales DESC; -- Chain: sales -> top 10 -> add product names A close relative is WITH (CTE), which common Table Expression — define a named temporary result set that can be referenced in the main query.