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

FirstNameDepartmentSalary
RahulSales72000
JamesSupport67000

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

CustomerIDOrderIDOrderDateAmount
11042024-02-1856.25
21032024-02-03412
31062024-03-09320.75
41072024-03-2227
51052024-03-01150
71082024-04-02198.4