SQL Correlated Subqueries
# What are Correlated Subqueries?
Correlated subqueries are a type of subquery that are used when data from the outer query is needed to execute the inner query. The inner query is correlated with the outer query because it is dependent on the outer query for its execution. The inner query runs for every row of the outer query and the result of the inner query is used by the outer query.
Correlated subqueries are often used when the inner query needs to find a value from the outer query and then use that value in its own where clause. This is necessary because the inner query needs to access columns from the outer query, and this is not possible with a regular subquery.
Using correlated subqueries can often result in a more efficient query than using multiple joins. This is because the correlated subquery will only run once for each row of the outer query, while a join would need to run multiple times.
Correlated subqueries can be used in many different types of queries, such as SELECT, UPDATE, and DELETE. They can also be used with aggregate functions, such as SUM and AVG.
Worried About Failing Tech Interviews?
Attend our webinar on
"How to nail your next tech interview" and learn
.png)
Hosted By
Ryan Valles
Founder, Interview Kickstart

Our tried & tested strategy for cracking interviews

How FAANG hiring process works

The 4 areas you must prepare for

How you can accelerate your learnings
Register for Webinar
### What is a Correlated Subquery?
A correlated subquery is a subquery (a query nested inside another query) that uses values from the outer query. It is used when the inner query depends on the outer query for it to execute.
### Syntax
The syntax for a correlated subquery is as follows:
```
SELECT outer_table.column_name
FROM outer_table
WHERE outer_table.column_name =
(SELECT inner_table.column_name
FROM inner_table
WHERE condition);
```
### Example
For example, if we have a table called `Users` that contains a list of users and a table called `Transactions` that contains a list of transactions for each user, we can use a correlated subquery to find all users who have made at least one transaction:
```
SELECT Users.user_name
FROM Users
WHERE EXISTS (SELECT *
FROM Transactions
WHERE Transactions.user_id = Users.user_id);
```