Careeroza
Correlated Subqueries
What Makes It Correlated
A correlated subquery refers to a column of the outer query, so it is evaluated once for each outer row. A normal subquery runs once in total.
Example
Employees who earn more than the average of their own department:
SELECT e.FirstName, e.Department, e.Salary
FROM Employees e
WHERE e.Salary > (
SELECT AVG(e2.Salary)
FROM Employees e2
WHERE e2.Department = e.Department -- refers to the outer row
);Result: 2 rows
| FirstName | Department | Salary |
|---|---|---|
| Rahul | Sales | 72000 |
| James | Support | 67000 |
Latest Order per Customer
Example
The most recent order of each customer:
SELECT o.CustomerID, o.OrderID, o.OrderDate, o.Amount
FROM Orders o
WHERE o.OrderDate = (
SELECT MAX(o2.OrderDate) FROM Orders o2
WHERE o2.CustomerID = o.CustomerID
)
ORDER BY o.CustomerID;Result: 6 rows
| CustomerID | OrderID | OrderDate | Amount |
|---|---|---|---|
| 1 | 104 | 2024-02-18 | 56.25 |
| 2 | 103 | 2024-02-03 | 412 |
| 3 | 106 | 2024-03-09 | 320.75 |
| 4 | 107 | 2024-03-22 | 27 |
| 5 | 105 | 2024-03-01 | 150 |
| 7 | 108 | 2024-04-02 | 198.4 |