I have a table below:
+----+------+
| id | p_id |
+----+------+
| 1  | null |
| 2  | 1    |
| 3  | 1    |
| 4  | 2    |
| 5  | 2    |
+----+------+
I need to write a query to display the following result:
+----+------+
| id | Type |
+----+------+
| 1  | Root |
| 2  | Inner|
| 3  | Leaf |
| 4  | Leaf |
| 5  | Leaf |
+----+------+
First query does not generate the expected output but second query does. The logic seems to be the same. Could you help me figure out the difference?
Query 1:
SELECT id,
CASE WHEN p_id is null THEN 'Root'
     WHEN id not in (select distinct p_id from tree) THEN 'Leaf'
     ELSE 'Inner' 
END AS Type
FROM tree;
+----+------+
| id | Type |
+----+------+
| 1  | Root |
| 2  | Inner|
| 3  | Inner|
| 4  | Inner|
| 5  | Inner|
+----+------+
Query 2:
SELECT id,
CASE WHEN p_id is null THEN 'Root'
     WHEN id in (select distinct p_id from tree) THEN 'Inner'
     ELSE 'Leaf' 
END AS Type
FROM tree;
+----+------+
| id | Type |
+----+------+
| 1  | Root |
| 2  | Inner|
| 3  | Leaf |
| 4  | Leaf |
| 5  | Leaf |
+----+------+
 
     
     
     
    