-->

Tuesday, February 18, 2014

How to use Correlated Subqueries in SQL Programming

How to use Correlated Subqueries in SQL Programming

In SQL programming, a correlated subquery can be defined as a query that depends on the outer query for its evaluation. In a correlated subquery, the WHERE clause references a table in the FROM clause. This means that the inner query is evaluated for each row of the table specified in the outer query.

For example, the following query displays the employee ID, designation, and number of hours spent on vacation for all the employees whose vacation hours are greater than the average vacation hours identified for their title:

SELECT BusinessEntityID, JobTitle, VacationHours
FROM HumanREsources.Employee el WHERE el.VacationHours>
(SELECT AVG(e2.VacationHours)
FROM HumanResources.Employee e2 WHERE el.JobTitle = e2.JobTitle)

In the preceding example, the inner query returns the Titles of the employees, from the Employee table, whose vacation hours are equal to the average vacation hours of all employees. The outer query retrieves the Employee ID, Title, and VacationHours of all the employees whose vacation hours is greater than the average vacation hours retrieved by the inner query. The output of the correlated subquery is shown in the following figure.

How to use Correlated Subqueries in SQL Programming

Read other related articles

Also read other articles

© Copyright 2013 Computer Programming | All Right Reserved