A CTE (Common Table Expression) is a temporary, named result set defined with the WITH keyword and used by the single statement that immediately follows it. It makes complex queries more readable and enables recursion. Syntax WITH CteName (OptionalColumn1, OptionalColumn2) AS ( SELECT ... -- the CTE query ) SELECT ... FROM CteName; -- the statement that uses it How to access a CTE - Reference it by name in the next statement, like a table or view: in FROM, JOIN, or as the target of UPDATE or DELETE (when it references one base table). - It exists only for that one statement. A second query after it cannot see the CTE. - If the previous statement in a batch does not end with a semicolon, start the CTE with ;WITH to avoid syntax errors. Example — customers whose total spending is above the average WITH CustomerTotals AS ( SELECT CustomerId, SUM(Total) AS TotalSpent FROM Orders GROUP BY CustomerId ) SELECT c.Name, t.TotalSpent FROM CustomerTotals t JOIN Customers c ON c.Id = t.CustomerId WHERE t.TotalSpent > (SELECT AVG(TotalSpent) FROM CustomerTotals); Notice the CTE is referenced twice in the same statement — something a derived table cannot do without repeating the subquery. Multiple CTEs, separated by commas WITH Sales2026 AS (SELECT * FROM Orders WHERE YEAR(OrderDate) = 2026), BigSales AS (SELECT * FROM Sales2026 WHERE Total > 10000) SELECT COUNT(*) FROM BigSales; Recursive CTE — employee hierarchy WITH OrgChart AS ( SELECT Id, Name, ManagerId, 0 AS Level FROM Employees WHERE ManagerId IS NULL -- anchor UNION ALL SELECT e.Id, e.Name, e.ManagerId, o.Level + 1 -- recursive part FROM Employees e JOIN OrgChart o ON e.ManagerId = o.Id ) SELECT * FROM OrgChart OPTION (MAXRECURSION 100); Using a CTE to delete duplicates WITH Ranked AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY Email ORDER BY Id) AS rn FROM Users) DELETE FROM Ranked WHERE rn > 1; Notes: a CTE is not stored or indexed; it is expanded into the query like an inline view, so it improves readability rather than performance. For reusing intermediate results across several statements or for indexing, use a temporary table.
Ravindra Wadile · · 0 likes