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 values of run does this query give for pid 3, pid 7 and pid 8?

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 values of run does this query give for pid 3, pid 7 and pid 8?
SELECT pid,
       SUM(budget) OVER (PARTITION BY dept ORDER BY pid) AS run
FROM Proj;
  1. A. pid 3: NULL, pid 7: 1300, pid 8: 750
  2. B. pid 3: NULL, pid 7: NULL, pid 8: 750
  3. C. pid 3: 0, pid 7: 1300, pid 8: 750
  4. D. pid 3: NULL, pid 7: 1300, pid 8: 100

Correct answer: A. pid 3: NULL, pid 7: 1300, pid 8: 750

PARTITION BY puts the two NULL-dept rows (pids 5 and 8) in one partition, exactly as GROUP BY would. With ORDER BY the frame runs from the start of the partition to the current row, and SUM skips NULLs. Ops (pids 3, 4, 6): pid 3 has only its own NULL budget in the frame, so the sum is NULL, not 0. R&D (pids 1, 2, 7): at pid 7 the frame holds 900, 400 and NULL, giving 1300 - a NULL in the current row does not make the running sum NULL. NULL partition (pids 5, 8): 650, then 650 + 100 = 750.

More DBMS and SQL questions

Exams that ask this topic