+ Start a Discussion
Manoj DegaManoj Dega 

How to Delete Account Related Attachments Using Batch Apex?

Hi Please Tell me anyone,

How to Delete Account Related Attachments Using Schedule Apex or How to Take Related Account Attachments to bring SOQL Query ?

Thanks in Advance
You can use Relationship queries in SOQL. in this case you can use parent to child queries
SELECT id, (SELECT Id FROM Attachments) FROM Account

For more info : 

Balaji Chowdary GarapatiBalaji Chowdary Garapati
@Manoj Dega:

  The only filters you can apply on id fields (in this case parentId by which you can say if it is an attachment for Account) is "IN" or " =" In the other words you can not filter on the attachments directly to fetch only account related ones., if instead you can modify your structure in such a way that "Deleting Attachments That Belongs To Particular Accounts" you can query attachments using "IN" operator., For eg.,

Set<id> AccountIdsForAttachmentDel=new Set<Id>();
//Loop through all your accounts for which attachments needs to be delted and collect the ids

then you can query

List<Attachment> AttachmentsForDeletion=[select id from Attachment where parentId IN : AccountIdsForAttachmentDel];

delete AttachmentsForDeletion;

Worst Case you need to start from Attachment, you might end up this way: 

For(Attachment AttachmentRecord:[select id,parentId from Attachment limit 50000]){
    if(String.valueof(AttachmentRecord.id).StartsWith('001'))//check if the prefix of id is 001 which determines if the record belongs to Account or not
//Code for your criteria

Note: If you have attachments more than 50K you need to have a logic that says  fetch remaining attachments and get those belongs to account to process them