🎯 Master Like a Pro:
SUBQUERIES
&
COMMON TABLE
EXPRESSIONS
SUBHRA DAS Swipe >
subhradas901@[Link]
1. SUBQUERIES :
A Query Within a Query
What is it ?
A subquery is a query nested inside
another SQL query. It helps retrieve
intermediate results before applying
further operations.
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
💡 The inner query calculates the average
salary, and the outer query filters employees
who earn more than that amount.
PERCENTILE_CONT(0.5): This is a continuous percentile
function that calculates the median value (50th percentile).
📌 Multi-row Subquery :
Example -
Find employees working in specific
departments :
💡 The subquery (SELECT DepartmentID FROM
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 :
💡 The subquery runs for each department,
checking the maximum salary dynamically.
The condition [Link] = [Link] makes
sure that MAX(Salary) is found within each department, not
across the whole company.
2. CTEs (Common
Table Expressions):
(a temporary named query inside a query.)
What is it ?
A Common Table Expression (CTE) is a
temporary table created within a query.
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 :
💡 The CTE calculates department-wise
bonuses first, making the final query simpler.
📌 Recursive CTE:
Example-
Extracting a company’s reporting hierarchy :
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 :
How the Query Works on This Data :
🔹 First Iteration (Base Case)
Finds John (EmployeeID = 1), because he has no
ManagerID.
🔹 Second Iteration (Recursive Case)
Finds Alice (2) and Bob (3), because their
ManagerID = 1.
🔹 Third Iteration (Recursive Case)
Finds David (4) and Emma (5), because their
ManagerID = 2.
🔹 No More Employees Left → The recursion
stops.
notes :
🔹 Experiment with subqueries in
WHERE, SELECT, and FROM
🔹 Use CTEs to simplify long,
unreadable queries
🔹 Try a recursive CTE to analyze
hierarchical data structures
Find this
useful?
Let’s Connected
SUBHRA DAS
subhradas901@[Link]