CTE stands for Common Table Expression.
It is defined at the top of a statement using the WITH clause, it acts like a temporary virtual table that you can query immediately inside a SELECT, INSERT, UPDATE, or DELETE statement
Key Benefits and Use Cases
Improves readability. Breaking a massive query into clean, top-to-bottom named steps makes SQL much easier to read, debug and maintain.
Allows code reuse within a query. You can reference the same CTE multiple times inside the main query without rewriting the underlying logic.
WITH HighValueOrders AS (
SELECT customer_id, SUM(amount) AS total_spent
FROM orders
GROUP BY customer_id
HAVING SUM(amount) > 1000
)
SELECT c.name, h.total_spent
FROM customers c
JOIN HighValueOrders h ON c.customer_id = h.customer_id;