Exercise · SQL & Querying
Predict, then run it
Predict the output
keys(key_id, opens_lock, sub_of) is a master-key hierarchy: GRAND is the root; A and B are sub-keys of GRAND; A1 is a sub-key of A. List every lock ultimately opened under GRAND, with depth:
WITH RECURSIVE walk(key_id, opens_lock, depth) AS (SELECT key_id, opens_lock, 0 FROM keys WHERE key_id = 'GRAND' UNION ALL SELECT k.key_id, k.opens_lock, w.depth + 1 FROM keys k JOIN walk w ON k.sub_of = w.key_id WHERE w.depth < 20) SELECT key_id, opens_lock, depth FROM walk ORDER BY depth, key_id;
Predict the exact output.