function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
AmansAmans 

SOQL queries in Apex code

hey Guys ,

just going through Apex code SOQL  queries and found some statements that confuse me a bit ,
u guys just have a look and help me out to reach any conclusion

statement 1

"It is important to note that SOQL queries only return data for SObject fields that are selected in the original query. Any fields that are not selected in the SOQL query (other than ID) are null when dereferenced in Apex Code, even if they contain values in the database."

Account a1 = [select id from accountwhere name = 'Acme'];
Double amt1 = 2 * a1.annualRevenue;
// The code above is incorrect: amt1 is now null, even if
// the account contains a value for annualRevenue in the
// database
Account a2 = [select id, annualRevenue from account
where name = 'Acme'];
Double amt2 = 2 * a2.annualRevenue;
48
Expressions
// The code above is correct: if the account contains a value
// for annualRevenue in the database, amt2 will not be null


statement 2
"Even if only one SObject field is selected, a SOQL query always returns a complete record. Consequently, you must dereference the field in order to access it.
"

Double rev = [select annualRevenue from account
where name = 'Acme'][0].annualRevenue;

*contradiction is  if I can access only those fields that are in the original query what is the need to dereference it ,
and if  query returns a complete record then i can derefernce any field without necessarly providing in query*

thx
gokubigokubi
Query retuns complete object with all the fields, but the values are null except for fields you specify in the query call. You can get into trouble if you leave a field off your query but try to use it in your code. With S-controls, you'd get an error, but with Apex you just get a null value.

Steve
SAroraSArora
thx , I got it   now  clouds of confusions are  clear