CS FundamentalsVery hardProduct company interview · GATE level

Table Proj(pid, lead, dept, budget, parent) rows: (1, 'Uma', 'R&D', 900, NULL), (2, 'Vik', 'R&D', 400, 1), (3, 'Uma', 'Ops', NULL, 1), (4, 'Wen', 'Ops', 400, 2), (5, 'Xia', NULL, 650, 2), (6, 'Vik', 'Ops', 250, 4), (7, 'Yash', 'R&D', NULL, NULL), (8, 'Wen', NULL, 100, 6). Table Team(lead, city) rows: ('Uma', 'Pune'), ('Vik', 'Goa'), ('Wen', NULL), ('Zed', 'Pune'). Both queries try to list the leads who have no R&D project. What do they return?

Table Proj(pid, lead, dept, budget, parent) rows: (1, 'Uma', 'R&D', 900, NULL), (2, 'Vik', 'R&D', 400, 1), (3, 'Uma', 'Ops', NULL, 1), (4, 'Wen', 'Ops', 400, 2), (5, 'Xia', NULL, 650, 2), (6, 'Vik', 'Ops', 250, 4), (7, 'Yash', 'R&D', NULL, NULL), (8, 'Wen', NULL, 100, 6). Table Team(lead, city) rows: ('Uma', 'Pune'), ('Vik', 'Goa'), ('Wen', NULL), ('Zed', 'Pune'). Both queries try to list the leads who have no R&D project. What do they return?
-- Q1
SELECT t.lead FROM Team t
LEFT JOIN Proj p ON p.lead = t.lead AND p.dept = 'R&D'
WHERE p.pid IS NULL;
-- Q2
SELECT DISTINCT t.lead FROM Team t
LEFT JOIN Proj p ON p.lead = t.lead
WHERE p.dept <> 'R&D' OR p.pid IS NULL;
  1. A. Q1: Wen, Zed. Q2: Zed
  2. B. Q1: Wen, Zed. Q2: Wen, Zed
  3. C. Q1: Zed. Q2: Uma, Vik, Wen, Zed
  4. D. Q1: Wen, Zed. Q2: Uma, Vik, Wen, Zed

Correct answer: D. Q1: Wen, Zed. Q2: Uma, Vik, Wen, Zed

Q1 joins each lead only to their R&D projects; a lead with none gets a NULL-padded row, which the IS NULL test keeps. Uma and Vik each lead an R&D project, so Q1 returns Wen and Zed - the correct anti-join. Q2 joins to all projects and then keeps any row whose dept differs from 'R&D'. Uma and Vik each also lead an Ops project, so they pass that row-level test and are listed even though they do have R&D work. Wen appears through the Ops project (pid 4); Wen's NULL-dept project fails the <> test but that does not matter. Q2 therefore returns all four leads.

More DBMS and SQL questions

Exams that ask this topic