Search

Tuesday, February 18, 2014
0 comments

How to use Correlated Subqueries in SQL Programming

8:22 AMTuesday, February 18, 2014
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

Protected by Copyscape Online Copyright Protection Software

0 comments :

Post a Comment

 
Toggle Footer
Top