SQL CTEs (Common Table Expressions) Explained With Real Examples | SQL Interview Series #5
Have you ever written a SQL query with so many nested subqueries that even you couldn’t understand it the next day? 😭
You’re not alone.
As SQL queries become more complex, readability and maintainability become just as important as getting the correct result.
That’s where Common Table Expressions (CTEs) come in.
A CTE allows us to break a complicated query into smaller, logical steps, making the SQL easier to read, debug, and maintain.
In this article, we’ll understand CTEs with practical examples and cover some of the most common interview questions around them.
What Is a CTE?
CTE stands for Common Table Expression.
It is a temporary named result set that you can reference within the SQL statement that follows it.
The basic syntax is:
WITH CTE_Name AS
(
SELECT column1, column2
FROM table_name
WHERE condition
)
SELECT *
FROM CTE_Name;Think of a CTE as giving a name to an intermediate query result.
For example, suppose we have an Employees table:
If we want to find employees earning more than ₹75,000:
WITH HighSalaryEmployees AS
(
SELECT *
FROM Employees
WHERE Salary > 75000
)
SELECT *
FROM HighSalaryEmployees;Here, HighSalaryEmployees is our CTE.
The main query can then treat it almost like a temporary result table.
Why Use a CTE?
The biggest advantage of a CTE is readability.
Consider a query using a nested subquery:
SELECT *
FROM
(
SELECT
Department,
AVG(Salary) AS AvgSalary
FROM Employees
GROUP BY Department
) AS DepartmentSalary
WHERE AvgSalary > 70000;It works, but as the query becomes larger, nested subqueries can become difficult to follow.
Now look at the same logic using a CTE:
;WITH DepartmentSalary AS
(
SELECT
Department,
AVG(Salary) AS AvgSalary
FROM Employees
GROUP BY Department
)
SELECT *
FROM DepartmentSalary
WHERE AvgSalary > 70000;Much cleaner.
The CTE gives the intermediate result a meaningful name and separates the logic into steps.
In simple terms:
Subquery: Put a query inside another query.
CTE: Give that intermediate query a name and make the overall query easier to understand.
Using Multiple CTEs
One of the most useful features of CTEs is that you can define multiple CTEs in the same statement.
Suppose we want to:
- Calculate the average salary for each department.
- Find departments where the average salary is above ₹70,000.
- Get employees belonging to those departments.
We can break this into two CTEs:
;WITH DepartmentSalary AS
(
SELECT
Department,
AVG(Salary) AS AvgSalary
FROM Employees
GROUP BY Department
),
HighPayingDepartments AS
(
SELECT
Department,
AvgSalary
FROM DepartmentSalary
WHERE AvgSalary > 70000
)
SELECT
e.EmployeeName,
e.Department,
e.Salary,
h.AvgSalary
FROM Employees e
JOIN HighPayingDepartments h
ON e.Department = h.Department;Instead of writing one huge query, we have created a simple flow:
Employees
↓
DepartmentSalary
↓
HighPayingDepartments
↓
Final ResultThis pattern is extremely useful when working with complex reporting or data transformation queries.
CTE + Window Functions
Here’s where CTEs become particularly useful in interviews.
Suppose the interviewer asks:
Find the highest-paid employee in each department.
We can use ROW_NUMBER() inside a CTE:
WITH RankedEmployees AS
(
SELECT
EmployeeID,
EmployeeName,
Department,
Salary,
ROW_NUMBER() OVER
(
PARTITION BY Department
ORDER BY Salary DESC
) AS RowNum
FROM Employees
)
SELECT
EmployeeID,
EmployeeName,
Department,
Salary
FROM RankedEmployees
WHERE RowNum = 1;The CTE first ranks employees within each department.
Then the outer query simply selects:
WHERE RowNum = 1This is a very common SQL pattern.
You can also modify it to find the second-highest salary, top 3 employees per department, duplicates, and many other scenarios.
Recursive CTEs
CTEs aren’t limited to simple queries.
They can also be recursive.
A recursive CTE is useful when working with hierarchical data such as:
- Employee-manager relationships
- Organization structures
- Folder hierarchies
- Category trees
Consider:
The hierarchy is:
CEO
├── Rahul
│ ├── Amit
│ └── Neha
└── PriyaA recursive CTE can traverse this hierarchy:
WITH EmployeeHierarchy AS
(
-- Anchor member
SELECT
EmployeeID,
EmployeeName,
ManagerID,
0 AS Level
FROM Employees
WHERE ManagerID IS NULL
UNION ALL
-- Recursive member
SELECT
e.EmployeeID,
e.EmployeeName,
e.ManagerID,
eh.Level + 1
FROM Employees e
JOIN EmployeeHierarchy eh
ON e.ManagerID = eh.EmployeeID
)
SELECT *
FROM EmployeeHierarchy;The important idea here is:
Anchor → Recursive step → Next level → Repeat
Get Varsha Vishwakarma’s stories in your inbox
Join Medium for free to get updates from this writer.
You don’t need to memorize the entire query for an interview. Understand the concept and know when recursive CTEs are useful.
CTE vs Temporary Table vs View
This is another popular interview question.
Easy way to remember:
CTE → Organize one query
Temporary Table → Store and reuse intermediate data
View → Save reusable query logic
Are CTEs Faster?
Here’s a common misconception:
“CTEs are faster than subqueries.”
Not necessarily.
A CTE is mainly a readability and query-organization feature.
The actual performance depends on factors such as:
- Indexes
- Joins
- Filters
- Data volume
- Query structure
- Database optimizer
- Execution plan
So don’t choose a CTE simply because you think it will automatically make the query faster.
Choose it when it makes the logic clearer and easier to maintain, and always check the execution plan when performance matters.
Common CTE Mistakes
1. Thinking the CTE is a permanent table
It isn’t.
A CTE normally exists only for the SQL statement immediately following it.
WITH EmployeeCTE AS
(
SELECT *
FROM Employees
)
SELECT *
FROM EmployeeCTE;Once that statement finishes, the CTE is gone.
2. Using a CTE for a simple query
Don’t turn this:
SELECT *
FROM Employees;into this:
;WITH EmployeeCTE AS
(
SELECT *
FROM Employees
)
SELECT *
FROM EmployeeCTE;That’s not making your SQL cleaner. 😂
Use CTEs when they actually simplify your logic.
3. Assuming CTE = performance improvement
As mentioned earlier, CTEs don’t automatically make queries faster.
Readability first. Performance should be validated separately.
SQL Interview Questions
1. What is a CTE?
A CTE is a named temporary result set defined using the WITH clause and available within a single SQL statement.
2. Why use a CTE?
Primarily to improve readability, organize complex logic, and avoid deeply nested queries.
3. Can we have multiple CTEs?
Yes.
WITH CTE1 AS
(
SELECT ...
),
CTE2 AS
(
SELECT ...
FROM CTE1
)
SELECT *
FROM CTE2;4. Can one CTE reference another CTE?
Yes. A later CTE can reference an earlier CTE in the same WITH clause.
5. What is a recursive CTE?
A recursive CTE references itself and is commonly used to work with hierarchical or parent-child data.
6. Are CTEs faster than subqueries?
Not necessarily. Performance depends on the query, database optimizer, indexes, data volume, and execution plan.
Final Takeaway
CTEs are one of those SQL features that look simple but become extremely useful as queries get more complicated.
Remember these key points:
- CTE = Common Table Expression
- Defined using the
WITHkeyword - Makes complex queries easier to read
- Can replace deeply nested subqueries
- Multiple CTEs can be chained together
- Works especially well with Window Functions
- Recursive CTEs are useful for hierarchical data
- CTEs don’t automatically improve performance
- Always use them when they make your SQL clearer — not simply because you can
The goal isn’t to write the shortest SQL query.
The goal is to write SQL that is correct, readable, maintainable, and easy for the next developer to understand.
And yes, sometimes that next developer is you six months later. 😭
What’s Next?
In Part 6, we’ll move into another extremely important SQL interview topic and explore Window Functions with practical examples.
Until then, keep practicing, stay curious, and remember:
Great SQL isn’t just about getting the right answer — it’s about writing queries that make sense. 🚀
If you found this article helpful, consider sharing it with your friends or colleagues, and don’t forget to follow this SQL Interview Series so you don’t miss the next article.
Happy Learning, and I’ll see you in Part 6! 🚀









