5

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?

1
  • You could look through all its child relationships and sub-query those.
    – Adrian Larson
    Commented Aug 11, 2015 at 15:38

1 Answer 1

5

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.

3
  • There's a limit to the number of subqueries per query, though, which was their concern. However, it'd be safe to say that even multiple queries won't hit the governor limits easily.
    – sfdcfox
    Commented Aug 11, 2015 at 15:53
  • True. Honestly OP is more likely to hit DML Rows limit, depending on the org.
    – Adrian Larson
    Commented Aug 11, 2015 at 16:13
  • Fantastic, thank you! I didn't know I could get Ids for different records in a single query this way
    – Valyrion
    Commented Aug 12, 2015 at 8:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .