my @nodes = (); my $sth = $dbh->prepare(q{ SELECT node_id, title, body FROM node WHERE parent_id = ? }); $sth->execute($parent_id); while (my $row = $sth->fetchrow_hashref) { push @nodes, $row; } $sth->finish; foreach my $node (@nodes) { $sth->execute($node->{node_id}); $node->{children} = $sth->fetchall_arrayref({ node_id => 1, title => 1 }); $sth->finish; } $t->param(NODES => \@nodes);