function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
paulkissickpaulkissick 

Is it possible to query the text within an attachment using SOQL?

I know it's possible to search attachments from the Web UI, but can I use either SOSL or SOQL to query the  attachment object from APEX in order to return a list of records (e.g. contacts) that have an attachment which contains some text i would like to find?

osamanosaman

You can access Attachment's data using Body field in Attachment object. The data stored in this field is encoded in base64. You can use EncodigUtil class to decode the data.

 

Thanks

paulkissickpaulkissick

That's useful to know.

But doesn't solve my issue, sadly.

I'm looking for something like:

 

List<Attachment> atts = [SELECT Id,ParentId,FileName FROM Attachment WHERE Body LIKE '%Manager%']

 

osamanosaman

Yes but you can retrieve the attachments and then traverse through each attachment to match the required text.

Maurizio BellaMaurizio Bella
I don't understand, how I can do a soql from attachment body?
as per official documentation I can't do it
Quote: "You can query notes and attachments to get information about them, but you cannot filter on the body of the note or attachment"
I just tried it and I got this error: "Error: Compile Error: Binary fields cannot be selected in join queries at line 11 column 11"
[CODE]
Qattach = [SELECT customObj__c.Name, (SELECT Attachment.Body FROM customObj__c.Attachments WHERE Attachment.Body LIKE 'D%') FROM customObj__c];
[/CODE]
I need to do a query into a attachment because I can't do it through search API
Thanks for any suggest.
Regards,
Mauri
paulkissickpaulkissick

Maurizio,

It's not possible to search attachment object bodies.

I have tried and failed on so many different attempts.

Paul