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: sNo | sName | dNo S01 | James | D01 S02 | Rocky | D01 S03 | Jackson | D02 S04 | June | D01 S05 | Milli | D02 Dept: dNo | dName D01 | CSE D02 | EEE Course: cNo | cName | dNo C11 | OS | D01 C12 | OS | D01 C21 | DE | D02 C22 | PT | D02 C23 | CV | D03 Register: sNo | cNo S01 | C12 S02 | C11 S03 | C21 S03 | C22 S04 | C11 S04 | C12 S05 | C21 Consider the following SQL query: SELECT sNo FROM Student AS S WHERE dNo = 'D01' AND sNo IN ( SELECT sNo FROM Register AS R WHERE cNo IN ( SELECT cNo FROM Course WHERE dNo = 'D01' ) ) EXCEPT SELECT sNo FROM Student WHERE dNo = 'D01' AND sNo NOT IN ( SELECT sNo FROM Register WHERE cNo IN ( SELECT cNo FROM Course WHERE dNo = 'D01' ) ) The number of rows returned by the above SQL query is ____________. A. 4 B. 5 C. 0 D. 3
GATE 2022 · Databases · SQL · medium
Answer: D. 3 — the query returns 3 rows (S01, S02, S04).
- Identify D01 courses: From the Course table: C11 (OS, D01), C12 (OS, D01). D01 courses = {C11, C12}.
- Identify D01 students: From the Student table: S01 (James, D01), S02 (Rocky, D01), S04 (June, D01). D01 students = {S01, S02, S04}.
- Evaluate First SELECT (Set A): Check each D01 student's registrations in {C11, C12}: S01: registered in C12 (D01 course) -> YES, S01 is in Set A S02: registered in C11 (D01 course) -> YES, S02 is in Set A S04: registered in C11, C12 (both D01 courses) -> YES, S04 is in Set A Set A = {S01, S02, S04}
- Evaluate Second SELECT (Set B): Check each D01 student: S01: has C12 (D01 course) -> NOT in Set B S02: has C11 (D01 course) -> NOT in Set B S04: has C11, C12 -> NOT in Set B Set B = {} (empty set)
- Apply EXCEPT: EXCEPT removes from Set A any rows that appear in Set B. Since Set B is empty, nothing is removed. Result = {S01, S02, S04} -> 3 rows.