GATE / CS ARCHIVE

GATE CSE 2005 / QUESTION 77

Correlated count of more expensive books

Database Management Systems · SQL & Queries · Full GATE CSE 2005 paper

GATE 2005, Q77 2 marks · MCQ
Report issue

SQL & Queries

Question 77, GATE 2005: book(title, price) has distinct prices. Query SELECT title FROM book B WHERE (SELECT COUNT(*) FROM book T WHERE T.price>B.price)<5. A four most expensive titles; B fifth cheapest; C fifth most expensive; D five most expensive titles. Examine NULL prices separately.
Tap to enlarge
Your answer
Answer & solution

Answer: D, assuming non-NULL prices (no official key was published)

For each B the subquery counts books with a strictly higher price. The predicate count<5 selects ranks 1 through 5 in descending price order, because they have respectively 0 through 4 more expensive books. Distinct prices rule out ties. The result is the titles of the five most expensive books (or all books if fewer than five), option D. This intended interpretation additionally assumes prices are non-NULL. Distinct prices alone does not establish a NOT NULL constraint: for a row B with NULL price, every T.price>B.price comparison is UNKNOWN, so the subquery counts zero and that NULL-priced row is included regardless of the five highest non-NULL prices.

For a book with descending rank r and a non-NULL unique price, exactly r−1 rows are more expensive. The predicate r−1<5 is r≤5, yielding the top five, not merely the fifth. COUNT(*) counts qualifying rows, never the current book because comparison is strict. If B.price is NULL, every comparison is UNKNOWN and no row qualifies, so count is 0 and that book also passes. Distinctness alone must not be silently upgraded to NOT NULL.

Original paper, page 10