IAE Academy

GATE 2020 CS Q.13: solution and answer

GATE 2020 · CSQ.13 · 1 mark · MCQ

Consider a relational database containing the following schemas.

Catalogue (primary key: sno, pno):

Suppliers (primary key: sno):

Parts (primary key: pno):

The primary key of each table is indicated by underlining the constituent fields.

SELECT s.sno, s.sname
FROM   Suppliers s, Catalogue c
WHERE  s.sno = c.sno AND
       cost > (SELECT AVG (cost)
               FROM Catalogue
               WHERE pno = 'P4'
               GROUP BY pno);

The number of rows returned by the above SQL query is

GATE 2020 CS question 13: Three relation tables (Catalogue, Suppliers, Parts) with the rows shown in the stem;Tap to open full size
Figure from the GATE 2020 CS paper. It is part of the question.
Figure description

Three relation tables (Catalogue, Suppliers, Parts) with the rows shown in the stem; primary key fields underlined: Catalogue (sno, pno), Suppliers sno, Parts pno.

  1. (A)

    4

  2. (B)

    5

  3. (C)

    0

  4. (D)

    2

Answer and solution

ANSWER

The query returns 4 rows (option A).

Official answer: ASource: Official answer key, GATE 2020 CS (IIT Delhi)

  1. Run the subquery first. Filtering Catalogue to pno = 'P4' leaves and .

  2. GROUP BY pno forms a single group because every remaining row has pno = 'P4'. The subquery therefore returns one value, . Since it is a scalar, the comparison cost > (subquery) is legal.

  3. The outer query joins Suppliers s and Catalogue c on s.sno = c.sno. Every Catalogue row has a matching supplier, so the join keeps all 9 rows. Suppliers has no cost column, so the unqualified cost means c.cost.

  4. Keep the joined rows with . For the costs are 150, 50 and 100, so none qualify. For , (200) fails and (250) passes. For , (250) passes, (150) fails, (300) passes and (250) passes.

  5. The qualifying rows are , , and , which is 4 rows.

  6. SELECT has no DISTINCT, so duplicate output rows stay. appears 3 times. The query returns 4 rows, which is option (A).

KEY IDEA

Evaluate the scalar subquery first (the average cost of part P4 is 225). Then filter the joined rows with cost above 225 and count them. Without DISTINCT, repeated supplier rows are all counted.

WATCH OUT FOR

Counting distinct suppliers (2: S2 and S3) instead of joined rows, because SELECT without DISTINCT keeps duplicates. Another slip is using instead of , or averaging over all of Catalogue instead of only P4.

From the GATE 2020 CS paper. Every question of this paper · Download the full paper · All 10 SQL questions, with notes

More SQL questions