I have a file firstname lastname cv.pdf attached to an Account record.

I would like to get the file using apex, below is my attempt:

List<ContentVersion> files = [SELECT Id, VersionData 
                              FROM ContentVersion 
                              WHERE FirstPublishLocationId = :accountId
                              AND Title = 'firstname lastname cv'
                              AND IsLatest = true];

Yet it returns zero records.

What am I doing wrong?


Look at the description for the field you are filtering on. Doesn't look right, but does give you an idea of where to look:

ID of the location where the version was first published. If the version is first published into a user's personal library or My Files, the field will contain the ID of the user who owns the personal library or My Files. If the first version is published into a public library, the field will contain the ID of that library.

Accepts all record IDs supported by ContentDocumentLink (anything a file can be attached to, like records and groups).

Setting FirstPublishLocationId allows you to create a file and share it with an initial record/group in a single transaction, and have the option to create more links to share the file with other records or groups later. When a file is created, it’s automatically linked to the record, and PublishStatus will change to Public from Pending/Personal.

This field is only set the first time a version is published via the API. FirstPublishLocationId can’t be set to another ID when a new content version is inserted.

So, maybe ContentDocumentLink is what you are looking for instead.

FROM ContentVersion
WHERE ContentDocumentId IN (
    SELECT ContentDocumentId FROM ContentDocumentLink WHERE LinkedEntityId = :accountId

If joins don't work (which wouldn't surprise me), you may need to add it as a separate query instead.

  • Maybe it's the right field, I don't know. But just trying to throw an alternative out there. – Adrian Larson Jan 10 '19 at 23:35

Just to add to it, with Spring 19 there is a new permission called Query All Files.

“With the new Query All Files permission, View All Data users can query ContentDocument and ContentVersion and retrieve all files in the org, including files in non-member libraries and files in unlisted groups. On its own, the View All Data permission only allows you to query files you own or have access to.”

More info can be found here:


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.