$sth = $dbh->prepare(q{ SELECT id, name FROM category WHERE parentCategoryId = ? ORDER BY name }); my @sub_categories; my @included_categories = ($root_category_id); my $included_categories_index = 0; while ($included_categories_index <= $#included_categories) { $sth->execute($included_categories[$included_categories_index]); while ($_ = $sth->fetchrow_hashref) { push @sub_categories, $_ if ($included_categories[$included_categories_index] == $root_category_id); push @included_categories, $_->{id}; } $included_categories_index++; }