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). In the row for a.pid = 1, what are x and y?

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). In the row for a.pid = 1, what are x and y?
SELECT a.pid, COUNT(b.pid) AS x, COUNT(c.pid) AS y
FROM Proj a
LEFT JOIN Proj b ON b.parent = a.pid
LEFT JOIN Proj c ON c.parent = b.pid
GROUP BY a.pid;
  1. A. x = 2, y = 3
  2. B. x = 2, y = 2
  3. C. x = 3, y = 2
  4. D. x = 3, y = 3

Correct answer: C. x = 3, y = 2

Project 1 has two children (pids 2 and 3). Project 2 has two children of its own (pids 4 and 5); project 3 has none. After both joins the group for pid 1 therefore has three rows: (1, 2, 4), (1, 2, 5) and (1, 3, NULL). COUNT(b.pid) counts non-NULL b.pid values in those rows, so x = 3 - child 2 is counted twice because the second join duplicated it. COUNT(c.pid) skips the NULL, so y = 2. To count children correctly one would need COUNT(DISTINCT b.pid).

More DBMS and SQL questions

Exams that ask this topic