IAE Academy

GATE 2022 CS Q.56: solution and answer

GATE 2022 · CSQ.56 · 2 marks · NAT

Consider the relational database with the following four schemas and their respective instances.

Student(sNo, sName, dNo) Dept(dNo, dName)
Course(cNo, cName, dNo) Register(sNo, cNo)

Student: (S01, James, D01), (S02, Rocky, D01), (S03, Jackson, D02), (S04, Jane, D01), (S05, Milli, D02)
Dept: (D01, CSE), (D02, EEE)
Course: (C11, DS, D01), (C12, OS, D01), (C21, DE, D02), (C22, PT, D02), (C23, CV, D03)
Register: (S01, C11), (S01, C12), (S02, C11), (S03, C21), (S03, C22), (S03, C23), (S04, C11), (S04, C12), (S05, C11), (S05, C21)

SQL Query:

SELECT * FROM Student AS S WHERE NOT EXIST
 (SELECT cNo FROM Course WHERE dNo = "D01"
      EXCEPT
  SELECT cNo FROM Register WHERE sNo = S.sNo)

The number of rows returned by the above SQL query is ______.

GATE 2022 CS question 56: Four tables.Tap to open full size
Figure from the GATE 2022 CS paper. It is part of the question.
Figure description

Four tables. Student(sNo, sName, dNo): S01 James D01; S02 Rocky D01; S03 Jackson D02; S04 Jane D01; S05 Milli D02. Dept(dNo, dName): D01 CSE; D02 EEE. Course(cNo, cName, dNo): C11 DS D01; C12 OS D01; C21 DE D02; C22 PT D02; C23 CV D03. Register(sNo, cNo): S01 C11; S01 C12; S02 C11; S03 C21; S03 C22; S03 C23; S04 C11; S04 C12; S05 C11; S05 C21.

Answer and solution

ANSWER

The query returns 2 rows (students S01 and S04).

Official answer: 2Source: Official answer key, GATE 2022 CS (IIT Kharagpur)

  1. The outer query keeps a student only when the subquery returns no rows. The subquery is , and it must be empty. This is the division pattern.

  2. Courses with dNo = "D01" are . C23 belongs to D03, so it does not count.

  3. So a student is kept exactly when both C11 and C12 appear in that student's registrations.

  4. The difference is empty only for S01 and S04, so the query returns 2 rows.

KEY IDEA

NOT EXISTS (A EXCEPT B) means . Here is the set of D01 courses, , and is the set of courses the student registered for. So the query returns the students who registered for every D01 course (relational division).

WATCH OUT FOR

Counting C23 (which belongs to D03) as a D01 course, or counting students by their own department. Another slip is reading the query as 'students who registered for any D01 course', which would give 4 rows.

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

More SQL questions