# Handling Zero Results SOQL on Attachments

I have a controller that sends an email and grabs a few different attachments from different records.

Not all the records will have an attachment called 'Venue Map' so I want to stop the error if the SOQL returns null. Not sure what to do here.

    Attachment att = [
select name, contenttype, body
from Attachment
where name LIKE '%Venue Map%' and ParentId = :cf.courses__r.venueid__c][0];

if(att.body.size() > 0 ){
Messaging.Emailfileattachment MyMap = new
Messaging.Emailfileattachment();
MyMap.setContentType(att.contentType);
MyMap.setFileName('Venue Information.pdf');
MyMap.setBody(att.Body);
fileAttachments.add(MyMap);
}

mail.setFileAttachments(fileAttachments);


The code is working perfect when there is a 'Venue Map' attachment, but if there isnt it just gives me this error "List index out of bounds: 0"

## 1 Answer

I suggest before using indexing of [0]. first, query and store into the list and then check if the size is more than 0 then perform everything like below

List<Attachment> attachments = [select name, contenttype, body
from Attachment
where name LIKE '%Venue Map%'
and ParentId = :cf.courses__r.venueid__c];
if(attachments.size() > 0){
att = attachments[0];

if(att.body.size() > 0 ){
Messaging.Emailfileattachment MyMap = new
Messaging.Emailfileattachment();
MyMap.setContentType(att.contentType);
MyMap.setFileName('Venue Information.pdf');
MyMap.setBody(att.Body);
fileAttachments.add(MyMap);
}

mail.setFileAttachments(fileAttachments);
}

• @JoeHayes your welcome – Ratan Paul Aug 10 '18 at 10:11