CTE in SQL Server
January 25, 2023
A Common Table Expression (CTE) in SQL Server is a feature that allows you to create a temporary result set that can be referred to within a SELECT, INSERT, UPDATE, or DELETE statement. The CTE is defined using the WITH clause and is followed by a SELECT, INSERT, UPDATE, or DELETE statement. The SELECT statement defines the structure of the CTE and the SELECT, INSERT, UPDATE, or DELETE statement that follows it can reference the CTE.
A CTE is useful for breaking down a complex query into simpler parts, making it easier to read and understand. It can also be used to simplify the process of querying hierarchical data, such as an organizational chart.
Here is an example of a CTE that is used to calculate the total sales for each product category:
WITH SalesCTE (Category, TotalSales) AS ( SELECT Category, SUM(Sales) FROM Products GROUP BY Category ) SELECT Category, TotalSales FROM SalesCTE
In this example, the subquery is embedded in the SELECT statement and calculates the total sales for each category. This can be less readable than a CTE and can be more complex if there are multiple subqueries. It is important to note that CTEs are only visible to the query immediately following the WITH clause and it is not stored in the database like a table, so it is not accessible to other queries or sessions.