![]() |
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:
Consider an Employees table containing employee details such as EmployeeID, Name, Department, Salary and ManagerID. We will use this table to demonstrate Common Table Expression (CTE) examples.
This 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 to retrieve hierarchical data, such as employee-manager relationships. Use MAXRECURSION to prevent infinite loops. It 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.
| 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. |