my $data = [ [ 'parent1', 'child1a', 'child2a', undef, ], [ 'parent1', 'child1b', 'child2b', 'child3b',], [ 'parent1', 'child1c', undef, undef,], ]; #### my $data = [ [ 'parent1', 'child1a' ], [ 'parent1', 'child2a' ], [ 'parent1', 'child1b' ], [ 'parent1', 'child2b' ], [ 'parent1', 'child3b' ], [ 'parent1', 'child1c' ], ]; #### while (my $row = $sth->fetch()) { my ($id, $parent_id) = @$row; ... } #### while (my $row = $sth->fetch()) { my ($parent_id, @children_ids) = @$row; for my $id (grep defined, @children_ids) { ... } }