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). How many rows of the result have diff = NULL, and what is diff for pid 6?
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).
How many rows of the result have diff = NULL, and what is diff for pid 6?
SELECT pid,
budget - LAG(budget) OVER (ORDER BY pid) AS diff
FROM Proj;- A. 3 rows are NULL; pid 6 shows -400
- B. 5 rows are NULL; pid 6 shows -400
- C. 5 rows are NULL; pid 6 shows -150
- D. 1 row is NULL; pid 6 shows -400
Correct answer: B. 5 rows are NULL; pid 6 shows -400
LAG returns the budget of the previous row in pid order, and any arithmetic with NULL is NULL. pid 1 has no previous row; pids 3 and 7 have NULL budgets themselves; pids 4 and 8 follow a row whose budget is NULL. That is 5 NULL results. LAG does not skip NULLs or look further back, so pid 6 is compared with pid 5: 250 - 650 = -400. The -150 answer compares pid 6 with pid 4, and the count of 3 forgets the rows that come right after a NULL.
More DBMS and SQL questions
- 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…
- 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…
- 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…
- 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…
- 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…
- 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…