Subqueries & CTE
Subqueries & CTE
SUBQUERIES
&
COMMON TABLE
EXPRESSIONS
Types of Subqueries:
✅ Single-row Subquery →
Returns one row
✅ Multi-row Subquery →
Returns multiple rows
✅ Correlated Subquery →
Depends on the outer query
📌 Single-row Subquery :
Example-
Find employees earning more than the
average salary
fetches
Departments WHERE Location = 'NY')
department IDs in NY, and the main query
selects employees from those departments.
📌 Correlated Subquery :
Example -
Find the highest-paid employee in each
department :
It improves:
✅ Readability – Makes complex queries
more structured
✅ Reusability – Allows the same logic to
be used multiple times
✅ Performance – Optimizes query
execution in some cases.
Syntax :
📌 Simple CTE :
Example-
Calculating total bonus payout per
department :
How it Works?
1️⃣Base Case: Finds the top-level manager
(ManagerID = NULL).
2️⃣
Recursive Case: Finds employees who
report to the manager.
3️⃣
Repeats until no more employees are left.
Example Data for Better Understanding :
Let’s Connected
SUBHRA DAS
[email protected]