table: child_node_id parent_node_id left_id right_id ------------- -------------- ------- -------- 2 1 3 1 4 1 5 1 6 2 7 2 8 4 9 5 10 7 9 10 my $children = $dbh->prepare(qq{ SELECT child_node_id FROM table WHERE parent_node_id = ? }); my $setleft = $dbh->prepare(qq{ UPDATE table SET left_id = ? WHERE child_node_id = ? }); my $setright = $dbh->prepare(qq{ UPDATE table SET right_id = ? WHERE child_node_id = ? }); my $ctr = 1; my $rootid = 1; walktree($rootid); sub walktree { my ($id) = @_; $setleft->execute($ctr++, $id); $children->execute($id); while(my ($subid) = $children->fetchrow_array) { walktree($subid); } $setright->execute($ctr++, $id); }