my $prepared_handle = $dbh->prepare('SELECT * FROM table WHERE parent_id = ?'); : : : get_children(0); sub get_children { my $parent_id = shift; $executed_handle = $prepared_handle->execute($parent_id); while (my $pointer = $executed_handle->fetchrow_hashref) { $results .= $pointer->{id}."\n"; get_children($pointer->{parent_id}); } }