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); ... }; #### select deb.id , mc.cid , mc.mail_month from fte_intra.debiteuren deb left join gmsms.mail_count mc on (mc.cid = deb.id) where deb.type='sms' AND (deb.Afloop_contract='0000-00-00' OR month(deb.Afloop_contract)='$lastmonth') AND mc.month='$lastmonth' AND mc.year='$yearG' group by deb.id order by deb.id