softwaretips4u Tips that Transform
← Back to Homepage ← Back to Articles

SQL Correlated Subqueries (Row-by-Row Power Tools)

πŸ”Ή Why Correlated Subqueries Matter

Correlated subqueries are inner queries that reference columns from the outer query. They execute once per outer row, making them perfect for row-aware comparisons like β€œemployees earning above their department average.”

βš™οΈ 1️⃣ How Correlated Subqueries Work

SELECT column_list
FROM table1 outer
WHERE outer.column > (
    SELECT AVG(inner.column)
    FROM table2 inner
    WHERE inner.key = outer.key
);
Unlike regular subqueries, correlated subqueries cannot run independently because they depend on the current outer row.

βš™οΈ 2️⃣ Sample Tables

EmployeesDepartments
EmpID, EmpName, DeptID, SalaryDeptID, DeptName
1 – Suresh – 10 – 6000010 – HR
2 – Priya – 10 – 8000020 – IT
3 – Raj – 20 – 5500030 – Finance
4 – Anil – 20 – 70000
5 – Meena – 30 – 90000

βš™οΈ 3️⃣ Example – Above Department Average

SELECT e.EmpName, e.Salary, e.DeptID
FROM Employees e
WHERE e.Salary > (
    SELECT AVG(e2.Salary)
    FROM Employees e2
    WHERE e2.DeptID = e.DeptID
);

Returns Priya, Anil, and Meena.

βš™οΈ 4️⃣ Example – Highest Salary per Department

SELECT e.EmpName, e.Salary, e.DeptID
FROM Employees e
WHERE e.Salary = (
    SELECT MAX(e2.Salary)
    FROM Employees e2
    WHERE e2.DeptID = e.DeptID
);

βš™οΈ 5️⃣ Example – Departments with High Earners

SELECT DISTINCT d.DeptName
FROM Departments d
WHERE EXISTS (
    SELECT 1
    FROM Employees e
    WHERE e.DeptID = d.DeptID
      AND e.Salary > 75000
);

βš™οΈ 6️⃣ Example – Row-by-Row Comparisons

SELECT e1.EmpName, e1.Salary
FROM Employees e1
WHERE e1.Salary > ALL (
    SELECT e2.Salary
    FROM Employees e2
    WHERE e2.DeptID = e1.DeptID
      AND e2.EmpName <> e1.EmpName
);

βš™οΈ 7️⃣ Example – Updates with Correlation

UPDATE Employees e
SET e.Salary = e.Salary * 1.10
WHERE e.Salary < (
    SELECT AVG(e2.Salary)
    FROM Employees e2
    WHERE e2.DeptID = e.DeptID
);

βš™οΈ 8️⃣ Performance Tips

TipDescription
Avoid on huge datasetsCorrelated subqueries execute per row, causing repeated scans.
Prefer joins/CTEsMany patterns can be rewritten with JOIN or WITH.
Index foreign keysBoosts lookup speed for the inner query.
Use EXISTS over INEXISTS short-circuits as soon as a match is found.
Leverage analyticsAVG() OVER (PARTITION BY DeptID) often replaces correlated logic.

βš™οΈ 9️⃣ Rewrite with Analytical Function

SELECT EmpName, Salary, DeptID
FROM (
    SELECT e.*, AVG(Salary) OVER (PARTITION BY DeptID) AS DeptAvg
    FROM Employees e
) t
WHERE Salary > DeptAvg;

🧩 Real-World Use Cases

Employee Analytics

Identify staff earning above department averages or below thresholds.

Sales Outliers

Spot stores outperforming regional averages.

Product Pricing

Detect items priced above category norms.

API Validation

Cross-check payload data based on related table conditions.

βš–οΈ Best Practices

πŸ’‘ Interview Tip

β€œA correlated subquery runs once per outer row. Explain when you would still choose it and how to mitigate performance (indexes, EXISTS, analytics).”
← Back to Articles | 🏠 Back to Homepage