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). What does this query 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). What does this query return?
WITH RECURSIVE up(pid, parent, budget) AS (
  SELECT pid, parent, budget FROM Proj WHERE pid = 8
  UNION ALL
  SELECT p.pid, p.parent, p.budget
  FROM Proj p JOIN up ON p.pid = up.parent)
SELECT COUNT(*), SUM(budget) FROM up;
  1. A. (5, 1650)
  2. B. (1, 100)
  3. C. (4, 1950)
  4. D. (5, 2050)

Correct answer: D. (5, 2050)

The anchor row is project 8. Each recursive step joins p.pid to the parent of a row already found, so it climbs towards the root: 8 -> 6 -> 4 -> 2 -> 1, and stops because project 1 has parent NULL, which joins to nothing. Five rows with budgets 100 + 250 + 400 + 400 + 900 = 2050. (1, 100) would be the result if the join went downwards (p.parent = up.pid), since project 8 has no children; (4, 1950) leaves out the anchor row.

More DBMS and SQL questions

Exams that ask this topic