# first, get all the results for the record set used in inner loop my $record_set_1 = $sth1->fetchall_arrayref; # loop over second record set while (my @row = $sth2->fetchrow_array) { foreach my $row_from_record_set_1 (@$record_set_1) { # blah blah } }