SQL - Common Table Expressions (CTEs) in SQL
1. What is a Common Table Expression?
A Common Table Expression (CTE) is a temporary named result set that you define within a SQL query.
It allows you to break complex queries into smaller, more readable parts.
A CTE exists only while the query is running and does not permanently store data in the database.
In simple terms, a CTE acts like a temporary table that helps organize complicated SQL statements.
2. Why Use CTEs?
-
Makes queries easier to read and maintain
-
Helps break complex logic into steps
-
Avoids repeating the same subquery multiple times
-
Useful for hierarchical or recursive queries
-
Improves query structure and clarity
3. Basic Syntax
Explanation:
-
WITHdefines the CTE -
cte_nameis the temporary name -
The main query uses it like a table
4. Example
Suppose you want to find employees earning above the average salary.
Without CTE:
With CTE:
This version separates the logic and improves readability.
5. Recursive CTEs
CTEs can reference themselves, which is useful for hierarchical data like organizational charts or folder structures.
Example structure:
This repeatedly builds levels of related data.
6. Difference Between CTE and Subquery
CTE
-
Named temporary result
-
Easier to read
-
Can be reused within query
-
Supports recursion
Subquery
-
Written inside another query
-
Harder to read when complex
-
Typically used once
-
No recursion
Summary
Common Table Expressions help simplify complex SQL queries by allowing you to define temporary result sets that can be referenced within the same query. They improve readability, support reuse, and enable recursive operations, making them a valuable tool for managing advanced SQL logic.