+ Start a Discussion
DavidvzlaDavidvzla 

Really dumb question about SOQL

I don't know what is the number inside the square brackets in SOQL used for?   for instance, number 0 (zero) inside square brackets. Thanks for your help.

1Account[] acctsWithContacts = [SELECT Name, (SELECT FirstName,LastName FROM Contacts)
2                               FROM Account
3                               WHERE Name = 'SFDC Computing'];
4// Get child records
5Contact[] cts = acctsWithContacts[0].Contacts;
6System.debug('Name of first associated contact: '
7             + cts[0].FirstName + ', ' + cts[0].LastName)

 
Best Answer chosen by Davidvzla
UC InnovationUC Innovation
That number is the index of the array that you are accessing.

For example, in line 5 you have acctsWithContacts[0].Contacts.

This means you are getting the first account in the acctsWithContacts array of accounts. 

acctsWithContacts[1] would get the second account, acctsWithContacts[2] gets you the third, etc. 

Hope that explains it! Please mark as best answer if this helped!

All Answers

UC InnovationUC Innovation
That number is the index of the array that you are accessing.

For example, in line 5 you have acctsWithContacts[0].Contacts.

This means you are getting the first account in the acctsWithContacts array of accounts. 

acctsWithContacts[1] would get the second account, acctsWithContacts[2] gets you the third, etc. 

Hope that explains it! Please mark as best answer if this helped!
This was selected as the best answer
DavidvzlaDavidvzla
Thanks, I completely forgot the Index unit of the tutorial but now I remember, really appreciate your prompt response, have a nice day.
Andreas EnglundAndreas Englund
Sorry for jumping on this old thread from nowhere. But on line 5: since they use an index to retrieve one instance of the Contacts array, why do they store that instance in a new array instead of a single Contact object? Then on line 7, use that newly created array and use index 0 again to retrieve the only one Contact again when a single object could've been used?