+ Start a Discussion
michael_mcmahonmichael_mcmahon 

Apex ?? from Force.com Workbook Lesson 8 Step 5 Code Coverage Tests

Why do I need to SELECT "id" in this example?  I am just learning, so please forgive me if this is a dumb question, but the test runs okay without it, and it seems wasteful to call it and not use it.  I'm not completely clear on the trigger (?) " IN :xxxxx " yet.  Does that method/function/subroutine/class/whatever require id to be SELECTed, or is id SELECTed here because the line of code could be used in more complex test scenarios but isn't really necessary for this simple test?

 

[SELECT id, unit_price__c FROM Line_Item__c WHERE id IN :lineItems];
System.assert(lineItems[0].unit_price__c == 10); // unchanged

 

Is this more efficient?   {SELECT unit_price__c FROM Line_Item__c WHERE id IN :lineItems}; 

 

Thank you for your help,

 

Michael

 

Best Answer chosen by Admin (Salesforce Developers) 
Sean TanSean Tan

In Apex, the Id field is always returned in queries regardless if you ask for it or not.

 

Try this in anonymous Apex:

 

Contact c = [ select Name from Contact limit 1 ];
System.debug(c.Id);

 It still will print the Id out.

 

Now to your specific question, I don't see any specific need to pull the Id field in the code sample you put, I also doubt one or the other is more optimal since Apex will always return the Id. If one was more optimal than the other, the difference would probably be so small it's neglible.

 

If it was any other field outside of Id, then yes it would be more optimal to not pull the fields you don't need.

All Answers

Sean TanSean Tan

In Apex, the Id field is always returned in queries regardless if you ask for it or not.

 

Try this in anonymous Apex:

 

Contact c = [ select Name from Contact limit 1 ];
System.debug(c.Id);

 It still will print the Id out.

 

Now to your specific question, I don't see any specific need to pull the Id field in the code sample you put, I also doubt one or the other is more optimal since Apex will always return the Id. If one was more optimal than the other, the difference would probably be so small it's neglible.

 

If it was any other field outside of Id, then yes it would be more optimal to not pull the fields you don't need.

This was selected as the best answer
michael_mcmahonmichael_mcmahon

Thank you Sean, I feel a little smarter.