RienSQL
LESSON 29 / 62 · Correlated Subqueries

Correlated Subqueries

Correlated and uncorrelated subqueries in SQL, their syntax

All previous subqueries we've discussed were uncorrelated (independent). They could be executed autonomously from the main query, and we could see what they returned before their result was used in the main query. Correlated subqueries, on the other hand, refer to one or more columns in the main query.

Example of a correlated subquery

For example, the following correlated subquery finds out who spent how much:

SELECT FamilyMembers.member_name, (
    SELECT SUM(Payments.unit_price * Payments.amount)
    FROM Payments
    WHERE Payments.family_member = FamilyMembers.member_id
) AS total_spent
FROM FamilyMembers;
member_nametotal_spent
Headley Quincey2504
Flavia Quincey74194
Andie Quincey3600
Lela Quincey650
Annie Quincey1060
Ernest Forrest
Constance Forrest
Wednesday Addams

In this case, the correlated subquery refers to the member_id column in the main query.

A correlated subquery differs from an uncorrelated subquery in that it is not executed once before the query in which it is nested, but for each row that can be included in the final result.

In our case, the main query to the FamilyMembers table returns 8 records, and a correlated subquery is executed for each of them.

Performance impact

It should be noted that the use of correlated subqueries can cause performance problems, especially if the containing query returns a lot of rows, since the correlated subquery will be executed separately for each row of the containing query.

Practice

Solve it in the editor. The query runs against a sample database in your browser.

Task 1Getting the most expensive purchased item
Using a correlated subquery, output the names of all family members (member_name) and the cost of their most expensive purchased item.
To display the cost of the most expensive purchased product, use the alias good_price. If there is no such product, output NULL.
SQL editor
SQLite
Ctrl / ⌘ + ↵
Result

Write a query and run it to see the results.

Task 2Above the average for its type
Print the identifier id, type home_type and price price of the places from the Rooms table that are more expensive than the average price of places of the same type.
SQL editor
SQLite
Ctrl / ⌘ + ↵
Result

Write a query and run it to see the results.