CS FundamentalsVery hardGATE CS · SQL

Table Route(src, dst, cost) rows: ('A', 'B', 5), ('B', 'C', 4), ('A', 'C', 12), ('C', 'D', 3), ('B', 'D', 9), ('D', 'A', 2). What does this query return?

Table Route(src, dst, cost) rows: ('A', 'B', 5), ('B', 'C', 4), ('A', 'C', 12), ('C', 'D', 3), ('B', 'D', 9), ('D', 'A', 2). What does this query return?
WITH RECURSIVE reach(node, hops) AS (
  SELECT 'A', 0
  UNION
  SELECT r.dst, hops + 1 FROM reach JOIN Route r ON r.src = reach.node
  WHERE hops < 2)
SELECT COUNT(*) FROM reach;
  1. A. 5
  2. B. 4
  3. C. 3
  4. D. 6

Correct answer: A. 5

Rows: (A,0); hop 1: (B,1), (C,1); hop 2: from B → (C,2), (D,2) and from C → (D,2) again. UNION drops the duplicate (D,2) but keeps (C,1) and (C,2) as different rows, so 5 (UNION ALL would give 6, distinct nodes only 4).

More DBMS and SQL questions

Exams that ask this topic