my $sth_C = $dbh->prepare( "select * from result_storage_keep where aggregated_area like ?") or die "Couldn't prepare query: " . $dbh->errstr; foreach my $area (@Geo_areas) { next unless $area; $sth_C->execute($area) or die "Couldn't execute query: " . $sth_C->errstr; while (my @row = $sth_C->fetchrow_array) { print OUTPUT_FILE join("\t", map {$_ ? $_ : "''"} @row), "\n"; } } #### # this only works if this array is small-ish my $areas = join(", ", @Geo_areas); # interpolating can be dumb ... # unless you trust the data in @Geo_areas... my $sth_C = $dbh->prepare( "select * from result_storage_keep where aggregated_area in ($areas) order by aggregated_area") or die "Couldn't prepare query: " . $dbh->errstr; while (my @row = $sth_C->fetchrow_array) { print OUTPUT_FILE join("\t", map {$_ ? $_ : "''"} @row), "\n"; }