Correlated subqueries sometimes let to create the query very briefly, which can look more cumbersome when you use other means. We shall remind that correlated subquery contains reference to the query which it contains (we shall name it the main query) with the result that subquery executes for each string of the main query.
Example 8.9.1
It is required to determine the date and the flights of every passenger, committed by them at its last flight day
To say the other way, you have to find the maximum dateof the flight for each passenger and to find all of his flights. With determination of the maximum date there is no problems :
we receive an error message, because number of flight is not used in aggregate function and also does not enter into the list of columns of the grouping. If we'll do the last one:
we receive last flight of the passenger by each flight which he flied. It is completely not that problem which we try to solve. Use of a сorrelated subquery
Here for each flight it is checked, whether it is accomplished last flight day of the given passenger. Thus if such flights there was a several, we receive all of them.
Seeming lack of the resulted solution is just also that the subquery should be calculated for every string of main query. To avoid it, it is possible to offer the alternative solution, which is using joining of the Pass_in_trip table with a subquery resulted at the beginning which calculates the maximal dates for each passenger:
It should be reminded that examples given here can be run directly on the website by selecting the check box “Without checking” on the page with exercises.