[SalesForce] Find all records referencing a specific Account

What would be the best way to go about listing all the records that reference an Account?

Lookup Ids aren't search indexed so SOSL turns up no results when looking for the Account Id and the only other option I've found is listing every possible relationship with a describe call and going through all of them one by one. This will almost immediately result in hitting the SOQL query limit of course.

Is there an option I'm overlooking?

Best Answer

You can find all the child relationships with a little Execute Anonymous:

Schema.DescribeSObjectResult describe = Account.sObjectType.getDescribe();
for (Schema.ChildRelationship child : describe.getChildRelationships())
{
    system.debug(
        child.getChildSObject() + '.' + child.getField() + ' - ' +
        child.getRelationshipName()
    );
}

You'll see a bunch of rows like:

AccountContactRole.AccountId - AccountContactRoles

You could then choose which of these you care about (there are a lot you probably do not), and use one SOQL query to grab them:

SELECT
    (SELECT Id FROM AccountContactRoles),
    (SELECT Id FROM Attributes__r),
    (SELECT Id FROM Assets)
FROM Account
WHERE Id = :accountId

This will only consume one query.

Related Topic