You do not want a "loop". You want to use a hierarchical query and find the leaves of the hierarchy tree for each root:
SELECT id,
CONNECT_BY_ROOT i1 AS i1,
i2
FROM table_name
WHERE CONNECT_BY_ISLEAF = 1
CONNECT BY
PRIOR i2 = i1
AND PRIOR id = id -- Not sure if this is needed as you only have one id value
Which, for the sample data:
CREATE TABLE table_name (id, i1, i2) AS
SELECT 'Y001', 'x1', 'a1' FROM DUAL UNION ALL
SELECT 'Y001', 'x1', 'a2' FROM DUAL UNION ALL
SELECT 'Y001', 'a1', 'a5' FROM DUAL UNION ALL
SELECT 'Y001', 'a2', 'a3' FROM DUAL UNION ALL
SELECT 'Y001', 'a3', 'a4' FROM DUAL;
Outputs:
| ID |
I1 |
I2 |
| Y001 |
a1 |
a5 |
| Y001 |
a2 |
a4 |
| Y001 |
a3 |
a4 |
| Y001 |
x1 |
a5 |
| Y001 |
x1 |
a4 |
fiddle
i1column then what path woul you choose while descending the hierarchy? Suppose there's another row withi1 = 'x0'andi2 = 'x1'