You are on page 1of 40

Introduction

to
&
 DML
 SOQL
 SOSL
// Create the account sObject
Account acct = new Account(Name='Acme', Phone='(415)555-1212',
NumberOfEmployees=100);
// Insert the account by using DML
insert acct;
// Get the new ID on the inserted sObject argument
ID acctID = acct.Id;
// Display this ID in the debug log
System.debug('ID = ' + acctID);

 Execute this snippet in the Developer Console using Anonymous Apex


 Inspect the User Debug statement in Debug Log.
for(Contact badCon : conList) {
if (badCon.Department = 'Finance') {
badCon.Description__c = 'New description';
}
update badCon;
}
// List to hold the new contacts to update.
List<Contact> updatedList = new List<Contact>();

for(Contact con : conList) {


if (con.Department == 'Finance') {
con.Description = 'New description';
// Add updated contact sObject to the list.
updatedList.add(con);
}
}
// Call update on the list of contacts. This results in one DML call for the
entire list.
update updatedList;
Account acct = new Account(Name='SFDC Account');
insert acct;
// Once the account is inserted, the sObject will be populated
with an ID.

// Get this ID.


ID acctID = acct.ID;

// Add a contact to this account.


Contact mario = new Contact(
FirstName='Mario',
LastName='Ruiz',
Phone='415.555.1212',
AccountId=acctID);
insert mario;
 Upsert uses the sObject record's primary key (the
ID), an idLookup field, or an external ID field to
determine whether it should create a new record
or update an existing one:
 If the key is not matched, a new object record is
created.
 If the key is matched once, the existing object record
is updated.
 If the key is matched multiple times, an error is
generated and the object record is neither inserted or
updated.
What is an exception?
 An exception is a special condition that changes the normal flow of
program execution. That is, it's when something bad happens that
the program can't deal with during execution. Exceptions are the
language's way of throwing up its hands and saying, "I can't deal
with this, you need to."
 So what kinds of conditions can cause Apex to raise, or throw, an
exception? Here are the most common examples:
 Your code expects a value from something that is currently null
 An insert or update statement fails to pass a custom validation rule you
have set
 Assigning a query that returns no records or more than one record to a
singleton sObject variable
 Accessing a list index that is out of bounds
 https://developer.salesforce.com/page/An_I
ntroduction_to_Exception_Handling
Syntax:

Example of Exception handling which sends email on exception


 If a DML operation fails, it returns an exception of
type DmlException.
try {

// This causes an exception because


// the required Name field is not provided.

Account acct = new Account();


// Insert the account

insert acct;

} catch (DmlException e) {

System.debug('A DML exception has occurred: ' +


e.getMessage());
}
Database.SaveResult[] results=
Database.insert(recordList, false);
 Below three statements are considered identical :
◦ insert recordList;
◦ Database.insert(recordList);
◦ Database.insert(recordList, true);
 Demo : PartialInsert
 Use DML
◦ To Catch bulk DML processing as Exceptions
 Use Database class methods
◦ To allow partial success of a bulk DML
operation
 DML operations execute within a transaction.
◦ Either complete successfully or
◦ if an error occurs in one operation the entire
transaction is rolled back and no data is
committed to the database.
 The boundary of a transaction can be a
trigger, a class method, an anonymous block
of code, an Apex page, or a custom Web
service method.
 SOQL (Salesforce Object Query Language)
 Query (SELECT) only
 Case insensitive
 Used in both Apex and Web
Service API
 Return records or number of
records found
 SOQL Basic Syntax
 You can use both SOQL and Apex in a trigger
 SOQL lets you do cross-object actions in your
trigger
 Mastering SOQL is the key to mastering Apex
 Developer Console provides the Query Editor
console
 Test your SOQL queries before adding them to
your Apex code.
 The barebones query:
◦ SELECT Id, Name, BirthDate FROM Contact
 The WHERE clause:
◦ SELECT Id, Name FROM Contact WHERE DoNotCall = false
 Using OPERATORs:
◦ SELECT Id, Name FROM Contact WHERE Phone != null
 Using AND and OR in the WHERE clause:
◦ SELECT Id, Name BirthDate, Likes_Ice_Cream__c FROM
Contact WHERE ( Phone != null AND DoNotCall = false)
OR Email != null
 Using TEXT, PICKLIST, or ID values:
◦ Always wrap those three data types in single
quotes!
◦ SELECT Id, Name, Phone, Birthdate,
Likes_Ice_Cream__c
FROM Contact WHERE Phone != null
AND RecordTypeId != '012i0000000ES3H'
◦ That record type is for married contacts…
 Using Numbers:
◦ Quotes are not needed for numbers
◦ SELECT Id, Name, Phone, Birthdate, Likes_Ice_Cream__c
FROM Contact WHERE Phone != null
AND Weight__c > 100
 Using Dates:
◦ SELECT Id, Name, Phone, Birthdate,
Likes_Ice_Cream__c
FROM Contact WHERE Phone != null
AND BirthDate = TODAY
◦ TODAY is a special date keyword
 Fuzzy Matching:
◦ SELECT Id, Name, Phone, Birthdate, Likes_Ice_Cream__c
FROM Contact WHERE
Phone LIKE '%(650)%‘
◦ The % is a SOQL wildcard that matches zero or
more characters.
 Sorting the results:
◦ SELECT Id, Name, Phone, Birthdate,
Likes_Ice_Cream__c
FROM Contact WHERE Phone != null
ORDER BY Name ASC
 Limiting your results:
◦ SELECT Id, Name, Phone, Birthdate,
Likes_Ice_Cream__c
FROM Contact WHERE Phone != null
LIMIT 5
Account[] accts = [SELECT Name,Phone FROM
Account
WHERE (Name='SFDC
Computing' AND
NumberOfEmployees>25)
ORDER BY Name
LIMIT 10];
System.debug(accts.size() + ' account(s)
returned.');
// Write all account array info
System.debug(accts);
 Parent-to-Child: Plural version of child
objects (downward traversal)
 Child-to-Parent: Singular version of
parent object (upward traversal)
 Relationships in Apex are written in dot
notation.
 Custom Relationships: both directions
are appended
with ’ _r’.

1. interviewer__c.position__r.status__c = ‘open’;
2. position__c.interviewers (just a collection to be iterated over)
3. review__c.job_application__r.position__r.status__c =
‘closed’;
 You can traverse a relationship from a child
object (contact) to a field on its parent
(Account.Name) by using dot notation.
◦ SELECT Id, Account.Name, Account.Industry,
Account.Website
FROM Contact
WHERE Account.NumberOfEmployees >= 200
◦ SELECT Account.Owner.Profile.CreatedBy.Name
FROM Contact
 To get child records related to a parent record, add an
inner query for the child records.
 For example, if we’re doing a SOQL query on accounts,
downwards traversal could pull data from the account’s
contacts.
◦ SELECT Id, Name, Industry, AnnualRevenue, ( SELECT Name,
Email, BirthDate FROM Contacts ) FROM Account
◦ The nested query is treated like another field. That’s why there
is a comma after the AnnualRevenue field.
◦ We use the plural version “Contacts” in the nested SOQL query.
If you need to find the keyword for a custom relationship, find
the lookup or master-detail field and look in the “Child
Relationship Name” field on the related field of the child object
(Account Lookup field on Contact)
◦ Use __r for custom objects. (For example, invoice statements are
linked to line items through the Line_Items__r relationship on
the Invoice_Statement__c custom object.)
for(account parent:
[SELECT Id, Name, Industry, AnnualRevenue,
( SELECT Name, Email, BirthDate FROM Contacts )
FROM Account WHERE Account.name like 'Grand
Hotels%']
)
{
//Since subquery is returning a list, if you want to check if child list is
empty.
if(!parent.contacts.isEmpty()){
for(contact child:parent.contacts){
system.debug('child :'+child.name);
}
}
else{
system.debug('no child');
}
}
for(list<account> parents: [SELECT Id, Name, Industry, AnnualRevenue,
( SELECT Name, Email, BirthDate FROM Contacts ) FROM
Account WHERE Account.name like 'Grand Hotels%']
)
{
for(account parent: parents)
{
//Since subquery is returning a list, if you want to check if child list is
empty.
if(!parent.contacts.isEmpty()){
for(contact child:parent.contacts){
system.debug('child :'+child.name);
}
}
else{
system.debug('no child');
}
}
}
 Static Query
List<Account> aa = [SELECT Id, Name FROM
Account WHERE Name = 'Acme'];

 Dynamic Query
List<Account> aa = database.query('SELECT
Id, Name FROM Account WHERE Name =
'Acme'');
 Dynamic Query
◦ Creation of a SOQL/ SOSL string at runtime with an
Apex script.
◦ Enables you to create more flexible applications means
developer can pass parameters dynamically.
 For example, you can create a search based on input from
an end user, or update records with varying field names on
different objects.
 When to use Dynamic SOQL
◦ When you don't know until runtime which fields you
want to include in your query, or your WHERE clause
should be constructed differently based on something
that happened earlier in the code. You could even
query on different objects, depending on what's
needed.
 Static Query (using select) .
//create a string
String s = 'mystring';

//add wildcards around it to be more flexible


in the search
s = '%' + s + '%';

//create an SOBject list with the results from


our query
SObject[] obj = [select id from SObjectName
where Name LIKE :s];
 Dynamic Query (Using database.query method).
//create a string
String s = 'mystring';

//create an SObject list with the results from our


query
List<SObject> obj= Database.query('SELECT Id FROM
SObjectName WHERE Name LIKE' + '%' + s + '%');

for(SObject o : obj){
Account a = (Account)o;
//do more here.....
}
 Force.com SOQL and SOSL Reference
◦ https://developer.salesforce.com/docs/atlas.en-
us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql.ht
m

You might also like