SQL
Correlated Subqueries
All the subqueries presented here so far have been **uncorrelated** subqueries, where the subqueries themselves are entirely self-contained and can be run without the parent query. There exists a second type of subqueries called **correlated** subqueries. For correlated subqueries, the subquery uses values from the parent subquery.  
Conceptually, the subqueries are run once for every single row in the parent query. Perhaps a simple way of envisioning this is that the correlated subquery is a **function** that is applied to every row in the source data set.  
For example, suppose that we want to find the minimum grade for every course. We could do that as follows:  
```sql
SELECT *
FROM grades grades_parent
WHERE grade =
(SELECT min(grade)
FROM grades
WHERE grades.course = grades_parent.course);
```  
| grade | course |
|------:|--------|
| 7     | Math   |
| 8     | CS     |  
The subquery uses a column from the parent query (` grades_parent.course`). Conceptually, we can see the subquery as a function where the correlated column is a parameter to that function:  
```sql
SELECT min(grade)
FROM grades
WHERE course = ?;
```  
Now when we execute this function for each of the rows, we can see that for `Math` this will return `7`, and for `CS` it will return `8`. We then compare it against the grade for that actual row. As a result, the row `(Math, 9)` will be filtered out, as `9 <> 7`.