SOQL
statements estimate to a list of sales force Objects, a single sObject,
or an Integer for count method queries. For example, we can get details
of Account named as ‘Acme’.
SOQL: List accObject = [select id, name from account where name = 'Acme'];
From this list, you can access individual elements.
Code:
if (!accObject.isEmpty()) {
// Execute commands
}
Description:
As
above code checks the list of Account object contains value. Following
example of code creates a new contact for the first account with the
number of employees greater than 10:
Code:
Contact c = new Contact (account = [select name, address from account where NumberofEmployees > 5 limit 1]);
c.FirstName = 'Raees';
c.LastName = 'Ahmed';
insert c;
Description:
Above code inserting contacts where account of employee greater than 5 and limit is 1.
Working with SOQL Aggregate Functions
Aggregate
functions in SOQL as same as in SQL, such as SUM () and MAX (), allow
you to roll up and summarize your data in the query.
SOQL:
AggregateResult[] groupResult = [SELECT AVG(Amount)aver FROM Opportunity];
Object avgAmount = groupedResults[0].get('aver');
Description:
Note
that any query that includes the aggregate function returns its results
in an array of AggregateResult objects. AggregateResult is a read-only
sObject and the only used for query results.
The
following example demonstrates a SOQL query for loop used to mass
update records. Suppose you want to change last name of contact across
all records of contact:
Code:
public void masUpdate() {
for (List contacts:[Select FirstName, LastName From Contact]) {
if (contacts.FirstName == 'ryan' && contacts.LastName == 'ander') {
contacts.LastName = 'raees';
}//end of if
} //end for
update contacts; //update contact
} // end of class
No comments:
Post a Comment