Day 9: Subqueries and Common Table Expressions (CTEs)
1. Subqueries
A subquery is a query nested inside another query. It can be used in SELECT, FROM, or WHERE clauses.
Types of Subqueries:
- Single-row Subquery: Returns one row.
- Multi-row Subquery: Returns multiple rows.
- Correlated Subquery: Depends on the outer query.
Example 1: Single-row Subquery
SQL
-- Find employees earning more than the average salary
SELECT Name, Salary
FROM Employees
WHERE Salary > (SELECT AVG(Salary) FROM Employees);
SQL
-- Find employees in specific departments
SELECT Name
FROM Employees
WHERE DepartmentID IN (SELECT DepartmentID FROM Departments WHERE Location = 'NY');
SQL
-- Find employees with the highest salary in each department
SELECT Name, Salary
FROM Employees E1
WHERE Salary = (
SELECT MAX(Salary)
FROM Employees E2
WHERE E1.DepartmentID = E2.DepartmentID
);
2. Common Table Expressions (CTEs)
CTEs provide a way to define temporary result sets that can be reused in the main query.
Syntax:
WITH CTEName AS (
SELECT Column1, Column2
FROM TableName
WHERE Condition )
SELECT * FROM CTEName;
Example 1: Simple CTE
SQL
-- Get total salary per department
WITH DepartmentSalary AS (
SELECT DepartmentID, SUM(Salary) AS TotalSalary
FROM Employees
GROUP BY DepartmentID
)
SELECT *
FROM DepartmentSalary;
SQL
WITH RecursiveCTE AS (
-- Anchor member
SELECT EmployeeID, ManagerID, Name
FROM Employees
WHERE ManagerID IS NULL
UNION ALL
-- Recursive member
SELECT E.EmployeeID, E.ManagerID, E.Name
FROM Employees E
INNER JOIN RecursiveCTE R
ON E.ManagerID = R.EmployeeID
)
SELECT *
FROM RecursiveCTE;
- Practice writing subqueries in WHERE, SELECT, and FROM.
- Use a CTE to simplify complex queries.
- Create a recursive CTE for hierarchical data if applicable.
No comments:
Post a Comment