BeginnerCoder

Lesson 20 — Correlated subquery

Correlated subqueries: a subquery per row

A correlated subquery refers to the outer row, so it is re-evaluated for each row. "Employees who earn more than the average of their own department" needs a different average for each person — the subquery filters by the outer row's department.

SELECT name FROM staff s
WHERE salary > (SELECT AVG(salary) FROM staff WHERE dept = s.dept)

Here s is the alias of the outer table, and s.dept is the current row's department.

Why it matters: "above their group's average", "latest order per customer" — per-row comparisons are everyday analytics.

Want it another way?
Task

Fill in the subquery's WHERE so it averages only the same department as the outer row. Expected: Ann and Dee.

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.

Keep going with Databases & SQL

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.