The relation book (title, price) contains the titles and prices of different books. Assuming that no two books have the same price, what does the following SQL query list?
select title
from book as B
where (select count(*)
from book as T
where T.price>B.price) < 5
View worked solution
Answer: D
To understand what the SQL query returns, let's analyze the correlated subquery:
select count(*) from book as T where T.price > B.price
For any book in the outer query, this subquery counts how many books have a price strictly greater than the price of . Let this count be .
The outer query selects the title of book if and only if . Since no two books have the same price, we can rank the books by price in descending order:
- 1st most expensive book: There are books more expensive than it (). Since , it is selected.
- 2nd most expensive book: There is book more expensive than it (). Since , it is selected.
- 3rd most expensive book: There are books more expensive than it (). Since , it is selected.
- 4th most expensive book: There are books more expensive than it (). Since , it is selected.
- 5th most expensive book: There are books more expensive than it (). Since , it is selected.
- 6th most expensive book: There are books more expensive than it (). Since , it is not selected.
Thus, the query selects the titles of the five most expensive books.
Free practice · Your answers on this page are not saved.
