my @customers= $dbh->selectall_arrayref(< {} }); select deb.id from fte_intra.debiteuren deb where deb.type='sms' AND (deb.Afloop_contract='0000-00-00' OR month(deb.Afloop_contract)='$lastmonth') group by deb.id order by deb.id SQL for my $ref (@customers) { { $invoice_cid = $ref->{'id'}; my $statement = "select mc.cid,mc.mail_month from gmsms.mail_count mc where mc.cid = '$invoice_cid' AND mc.month='$lastmonth' AND mc.year='$yearG'"; my $sth = $DBH->prepare($statement); ... };