Correlated nested queries

Data-Driven Decision Making in SQL

Bart Baesens

Professor Data Science and Analytics

Correlated queries

  • Condition in the WHERE clause of the inner query.
  • References some column of a table in the outer query.
Data-Driven Decision Making in SQL

Example correlated query

  • Number of movie rentals more than 5
    SELECT *
    FROM movies as m
    WHERE 5 < 
      (SELECT COUNT(*)
      FROM renting as r
      WHERE r.movie_id=m.movie_id);
    
Data-Driven Decision Making in SQL

Evaluate inner query

SELECT COUNT(*)
FROM renting as r
WHERE r.movie_id = 1;
| count |
|-------|
| 8     |
Data-Driven Decision Making in SQL

Evaluate outer query

Number of movie rentals larger than 5

SELECT *
FROM movies as m
WHERE 5 < 
    (SELECT COUNT(*)
    FROM renting as r
    WHERE r.movie_id = m.movie_id);
| movie_id | title                 | genre  | runtime | year_of_release | renting_price |
|----------|-----------------------|--------|---------|-----------------|---------------|
| 1        | One Night at McCool's | Comedy | 93      | 2001            | 2.09          |
| 2        | Swordfish             | Drama  | 99      | 2001            | 2.19          |
Data-Driven Decision Making in SQL

Less than 5 movie rentals

Select movies with less than 5 movie rentals.

SELECT *
FROM movies as m
WHERE 5 > 
    (SELECT COUNT(*)
    FROM renting as r
    WHERE r.movie_id = m.movie_id);
| movie_id | title           | genre              | runtime | year_of_release | renting_price |
|----------|-----------------|--------------------|---------|-----------------|---------------|
| 17       | The Human Stain | Mystery & Suspense | 106     | 2003            | 1.99          |
| 20       | Love Actually   | Comedy             | 135     | 2003            | 2.29          |
Data-Driven Decision Making in SQL

Let's practice!

Data-Driven Decision Making in SQL

Preparing Video For Download...