A CTE (Common Table Expression) is a temporary named result set that you can reference within a single SQL statement.
Think of it as:
- A named subquery
- A way to make complex SQL cleaner and readable
- A tool for hierarchical (recursive) queries
📌 A CTE exists only while the query runs.
1.Basic CTE Syntax
Rules
✔ WITH keyword starts a CTE
✔ Must be followed immediately by a query
✔ Cannot be reused outside the statement
2.Simple CTE Example
Employees Table
| EmployeeID | Name | Salary |
|---|---|---|
| 1 | John | 50000 |
| 2 | Jane | 60000 |
Query
3.CTE vs Subquery
Subquery
CTE (Better readability)
✔ CTE is easier to read and maintain
4.CTE with WHERE Clause
5.CTE with JOIN
6.Multiple CTEs in One Query
7.Recursive CTE (Very Important)
Used for hierarchical data like:
✔ Employee → Manager
✔ Category → Subcategory
✔ Tree structures
Employees Table
| EmployeeID | Name | ManagerID |
|---|---|---|
| 1 | CEO | NULL |
| 2 | Manager | 1 |
| 3 | Developer | 2 |
