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). Which pids 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). Which pids does this query return?
SELECT pid FROM Proj p
WHERE 1 = (SELECT COUNT(DISTINCT q.budget)
           FROM Proj q
           WHERE q.dept = p.dept AND q.budget > p.budget);
  1. A. pids 2 and 6
  2. B. pids 2, 4 and 6
  3. C. pids 2, 6 and 8
  4. D. pids 1 and 4

Correct answer: A. pids 2 and 6

For each row the subquery counts the distinct budgets in the same department that are strictly larger; a count of 1 means the row holds the second-highest budget of its department. R&D has 900, 400 and NULL: pid 2 (400) has exactly one larger value. Ops has NULL, 400 and 250: pid 6 (250) has one larger value. Rows with a NULL budget or a NULL dept make the WHERE of the subquery unknown for every q, so their count is 0 and they are not returned - which is why pid 8 does not appear even though 650 > 100 among the NULL-dept rows. Pids 1 and 4 are the highest of their departments (count 0).

More DBMS and SQL questions

Exams that ask this topic