![]() |
VOOZH | about |
A Common Table Expression (CTE) is a temporary result set in SQL that you can reference within a single query. CTEs simplify complex queries, make them easier to read, and can be reused multiple times within the same query. It is used for:
Let’s consider an Employees table that contains employee details such as EmployeeID, Name, Department, Salary, and ManagerID. This table is used to demonstrate how to use a Common Table Expression (CTE) to simplify SQL queries, particularly when aggregating or filtering data.
👁 Screenshot-2026-01-17-093136This table represents the hierarchical structure of employees within an organization, based on a recursive CTE query.
👁 Screenshot-2026-01-17-093937This example uses a CTE to find the average salary of each department, making the query simpler and easier to read.
Query:
WITH AvgSalaryByDept AS (
SELECT Department, AVG(Salary) AS AvgSalary
FROM Employees
GROUP BY Department
)
SELECT *
FROM AvgSalaryByDept;Output:
👁 Screenshot-2026-01-17-094040Syntax:
WITH cte_name AS (
SELECT query
)
SELECT *
FROM cte_name;A recursive CTE references itself and is useful for querying hierarchical data, such as employees and their managers stored in the same table. It repeatedly executes until the full hierarchy is returned. To avoid infinite loops from incorrect definitions, use the MAXRECURSION hint in the query’s OPTION clause.
Recursive CTEs consist of two parts:
WITH
cteReports (EmpID, FirstName, LastName, MgrID, EmpLevel)
AS
(
SELECT EmployeeID, FirstName, LastName, ManagerID, 1
FROM Employees
WHERE ManagerID IS NULL
UNION ALL
SELECT e.EmployeeID, e.FirstName, e.LastName, e.ManagerID,
r.EmpLevel + 1
FROM Employees e
INNER JOIN cteReports r
ON e.ManagerID = r.EmpID
)
SELECT
FirstName + ' ' + LastName AS FullName,
EmpLevel,
(SELECT FirstName + ' ' + LastName FROM Employees
WHERE EmployeeID = cteReports.MgrID) AS Manager
FROM cteReports
ORDER BY EmpLevel, MgrID Output:
👁 Screenshot-2026-02-05-102316CTEs (Common Table Expressions) help simplify and organize complex SQL queries.
While useful, CTEs come with a few practical constraints.
Here, are some key differences between CTE and Subqueries are give below:
| CTE | Subquery |
|---|---|
| Can be referenced multiple times. | Typically used once. |
| Improves readability for complex queries. | Can become difficult to read when nested. |
| Optimized for multiple references. | May be less efficient for repeated operations. |