IAE Academy

GATE 2018 CS Q.12: solution and answer

GATE 2018 · CSQ.12 · 1 mark · MCQ

Consider the following two tables and four queries in SQL.

Book (, bname), Stock (, copies)

Query 1: SELECT B.isbn, S.copies
FROM Book B INNER JOIN Stock S
ON B.isbn = S.isbn;

Query 2: SELECT B.isbn, S.copies
FROM Book B LEFT OUTER JOIN Stock S
ON B.isbn = S.isbn;

Query 3: SELECT B.isbn, S.copies
FROM Book B RIGHT OUTER JOIN Stock S
ON B.isbn = S.isbn;

Query 4: SELECT B.isbn, S.copies
FROM Book B FULL OUTER JOIN Stock S
ON B.isbn = S.isbn;

Which one of the queries above is certain to have an output that is a superset of the outputs of the other three queries?

  1. (A)

    Query 1

  2. (B)

    Query 2

  3. (C)

    Query 3

  4. (D)

    Query 4

See the question in the paper

Answer and solution

ANSWER

The answer is (D) Query 4, the full outer join.

Official answer: DSource: Official answer key, GATE 2018 CS (IIT Guwahati)

  1. Let be the set of matching pairs (), the Book rows with no matching Stock row, and the Stock rows with no matching Book row.

  2. Query 1 (inner join) returns the rows of only.

  3. Query 2 (left outer join) returns plus the rows of . Each row is padded with NULL for S.copies.

  4. Query 3 (right outer join) returns plus the rows of . For these rows B.isbn is NULL, because the selected isbn comes from Book.

  5. Query 4 (full outer join) returns plus plus , with NULL padding on whichever side has no match.

  6. Query 4 therefore contains every row of Queries 1, 2 and 3: and .

  7. Queries 2 and 3 are not supersets of each other. Query 2 can contain rows that Query 3 lacks, and Query 3 can contain rows that Query 2 lacks. Query 1 lacks both. Only the full outer join is certain to contain the outputs of all the others, so the answer is Query 4.

KEY IDEA

A full outer join returns the matched rows plus the unmatched rows from both tables. Its result therefore contains the inner, left outer and right outer join results.

WATCH OUT FOR

Choosing Query 2 or Query 3 because an outer join looks bigger than an inner join. A left outer join drops Stock-only rows and a right outer join drops Book-only rows. Neither contains the other, so only the full outer join covers all three.

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

More SQL questions