p_id is NULL.id is not present in any p_id (indicating it has no children) and it has a p_id (indicating it has a parent).id is present in any p_id (indicating it has children) and it has a p_id (indicating it has a parent).UNION operator and sort by id.erDiagram
Tree {
int id PK "Unique node identifier"
int p_id FK "Parent node identifier"
}