wasAsked.

What is CTE?

Agiliad Technologies Pvt Ltd · Role not specified · technical

Published

Asked in 2026 · SQL

Community answers

Posted by wasAsked editorial collection

A CTE, or Common Table Expression, is a named temporary result set that you define at the start of a query with the WITH clause and then use in the main query. It exists only for the duration of that single statement. Basic example WITH HighValueOrders AS ( SELECT OrderId, CustomerId, Total FROM Orders WHERE Total > 5000 ) SELECT CustomerId, COUNT(*) AS BigOrders FROM HighValueOrders GROUP BY CustomerId; Why use CTEs 1. Readability: break a complex query into named, logical steps instead of deeply nested subqueries. 2. Reuse within one statement: reference the same CTE more than once, for example comparing values to an average computed from the same data. 3. Recursion: recursive CTEs handle hierarchical or graph-like data — organisation charts, category trees, bill of materials, date series. 4. Window-function filtering: compute ROW_NUMBER, RANK or DENSE_RANK in a CTE and filter in the outer query (window functions cannot be used directly in WHERE). 5. Data modification: delete duplicates or update rows through a CTE that targets one table. Recursive example — generate dates for a month WITH Dates AS ( SELECT CAST('2026-11-01' AS DATE) AS d UNION ALL SELECT DATEADD(DAY, 1, d) FROM Dates WHERE d < '2026-11-30' ) SELECT d FROM Dates; A recursive CTE has an anchor member, UNION ALL, and a recursive member that refers to the CTE itself. SQL Server limits recursion to 100 levels by default; change it with OPTION (MAXRECURSION n). CTE vs alternatives - Subquery or derived table: similar results, but a CTE is easier to read and can be referenced several times. - View: stored permanently in the database and reusable across queries; a CTE is defined inline for one statement. - Temporary table: physically stores data, can be indexed and reused across several statements; better when an intermediate result is large or reused many times. Performance note: in SQL Server a CTE is not materialised — it is expanded into the query, so referencing it several times may execute that logic several times. If that becomes expensive, use a temp table instead.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics