In SQL, a correlated subquery is a subquery that references a column from the outer query. The subquery is executed for each row of the outer query, which makes it slower than a regular subquery. However, it allows you to filter or sort the results of the subquery based on the values of the outer query.

Here’s an example to illustrate the use of correlated subqueries:

Suppose we have two tables, “employees” and “orders”. The “employees” table has columns “employee_id” and “employee_name”, while the “orders” table has columns “order_id”, “employee_id”, and “order_date”.

We want to find the names of employees who have made an order before their hire date. We can use a correlated subquery to achieve this:

SELECT employee_name
FROM employees e
WHERE EXISTS (
  SELECT 1
  FROM orders o
  WHERE o.employee_id = e.employee_id
    AND o.order_date < e.hire_date
)

In this query, we use a correlated subquery to check if there is an order made by the current employee before their hire date. The subquery is executed for each row of the “employees” table, and returns true or false depending on whether the condition is met.

Note that the subquery uses the “employee_id” column from the outer query to filter the “orders” table. This is what makes it a correlated subquery.

Another example of correlated subquery is to find the top N records from each group. For example, if we have a table “sales” with columns “region”, “salesperson”, and “sales_amount”, we can use a correlated subquery to find the top 3 salespeople in each region:

SELECT region, salesperson, sales_amount
FROM sales s1
WHERE (
  SELECT COUNT(*)
  FROM sales s2
  WHERE s2.region = s1.region
    AND s2.sales_amount > s1.sales_amount
) < 3

In this query, we use a correlated subquery to count the number of salespeople with higher sales amounts for each record in the “sales” table. The outer query then filters the results to only include the top 3 salespeople in each region.

In summary, correlated subqueries are useful for filtering or sorting results based on the values of the outer query. However, they can be slower than regular subqueries due to the need to execute the subquery for each row of the outer query.

Also check WHAT IS GIT ? It’s Easy If You Do It Smart

You can also visite the Git website (https://git-scm.com/)

Leave a Reply

Your email address will not be published. Required fields are marked *