A relational schema for a train reservation database is given below.
- passenger(pid, pname, age)
- reservation(pid, class, tid)
What pids are returned by the following SQL query for the above instance of the tables?
SELECT pid
FROM Reservation
WHERE class='AC' AND
EXISTS (SELECT *
FROM Passenger
WHERE age>65 AND
Passenger.pid=Reservation.pid)View worked solution
Answer: C
To find the pids returned by the SQL query, we evaluate the query step-by-step.
Step 1: Analyze the Outer Query
The outer query selects pid from the Reservation table where the class is 'AC':
SELECT pid FROM Reservation WHERE class = 'AC'
From the given Reservation table, the rows with class = 'AC' are:
pid = 0(tid = 8200)pid = 1(tid = 8201)pid = 5(tid = 8203)pid = 3(tid = 8202)
These pid values are our candidates.
Step 2: Evaluate the Correlated Subquery
For each candidate pid from the outer query, the EXISTS clause checks if there is a matching record in the Passenger table where age > 65 and Passenger.pid = Reservation.pid.
- For
pid = 0:In the
Passengertable, the passenger withpid = 0(Sachine) hasage = 65.Since is False, the subquery returns no rows.
EXISTSevaluates to False. - For
pid = 1:In the
Passengertable, the passenger withpid = 1(Rahul) hasage = 66.Since is True, the subquery returns a row.
EXISTSevaluates to True. Thus,1is selected. - For
pid = 5:There is no record for
pid = 5in thePassengertable.The subquery returns no rows.
EXISTSevaluates to False. - For
pid = 3:In the
Passengertable, the passenger withpid = 3(Anil) hasage = 69.Since is True, the subquery returns a row.
EXISTSevaluates to True. Thus,3is selected.
Conclusion
The pids that satisfy all conditions are and .
Free practice · Your answers on this page are not saved.
