Why does SOQL return related records when run directly but not when run with Apex

apexsoql

I have a SOQL query that looks like this:

SELECT Id, OwnerId, IsDeleted, AboutThirtyFieldsTotal__c, ...
(SELECT Id, IsDeleted, OverFiftyFields__c, ...
 FROM Borrowers__r )
FROM Loan__c WHERE LSC__c = '0051F00000ocJMdQAM'
ORDER BY CreatedDate LIMIT 200

The entire query is about 1,500 characters long.

When I run this query directly (by selecting it in VS Code and executing it with the command pallet) I get the correct result, with columns for Borrowers__r.FirstName__c with multiple rows for each of the related records.

If I run the exact same query from within Database.query, I don't get the related data, only the data from Loan__c with no data after the last field in the outer SELECT?

Why do I get related data when I directly execute the SOQL but not when it's executed by Apex?

Best Answer

When you debug an SObject record, the output is not necessarily going to show you everything in memory, as it coerces the complex data type into a String to render.

What you observe when you system.debug(someRecord) in this case is incomplete. If you were to system.debug(someRecord.Parent__r.Field__c, you would see these fields are in fact populated.

Alternatively, you can system.debug(JSON.serialize(someRecord)) and see a more complete representation.

Related Topic