Session 4 SOQL and SOSL
Session 4 SOQL and SOSL
Quering data in our salesforce instance, to fetch the data which is present in our system.suppose if
we have Standard objects like Account,Contacts,Oppurnity and custom objects,if we want to get the
data with SOQL.
SOQL stands for Salesforce Object Query Language
- Syntax:
SELECT <columnNames>
FROM <objectName>
[ WHERE <condition> ]
[ GROUP BY <columnNames> ]
[ HAVING <conditions> ]
[ ORDER BY <columnNames> ]
[ LIMIT <numberOfRecordsToReturn> ]
[ OFFSET <recordsToSkip> ]
- Only "SELECT" clause and "FROM" clauses are manadatory clauses, all other clauses are
optional.
- Field API name must be used in "SELECT" clause.
Examples:
ORDER BY Clause:
- This clause is used to arrange resultset records in either ascending order or descending order.
- "ASC" is used for ascending order, whereas, "DESC" is used for descending order, used along
with ORDER BY Clause.
- If user don't specify any sorting order, Salesforce arranges the records in ascending order by
default.
OFFSET Clause:
- This clause is used to specify number of columns to be get skipped from resultset.
SELECT Name FROM Merchandise__c WHERE Price__c > 5.0 ORDER BY Name LIMIT 100
OFFSET 10
The result set for the preceding example would be a subset of the full result set, returning rows 11
through 110 of the full set.
GROUP BY Clause:
- This clause is used to group the records based on one or more columns specified by user.
- This clause is used with "Aggregate Functions".
- Aggregate functions takes set of values as an input, perform operation of it and return one value as
a result.
- Apex supports below aggregate functions:
1. COUNT()
- This function returns number of records exist in an object.
- "Database.countQuery()" method is used, if this function is executed using dynamic query.
- COUNT(<colunmName>) function counts the values exist in specified column, excluding
"NULL" values.
- COUNT_DISTINCT(<colunmName>) function counts the values exist in specified column,
excluding "NULL" and "Duplicate" values.
Example:
select count() from student__c
2. SUM(<colunmName>):
- This function returns sum of all values exist in specified column.
- This function can be used only with "numeric" values.
- Specified column type should be "Number", "Currency" and "Percent" type.
Example:
select sum(Amount__C) from vyom_labs_sales__c
3. AVG(<colunmName>):
- This function returns average of all values exist in specified column.
- This function can be used only with "numeric" values.- Specified column type should be
"Number", "Currency" and "Percent" type.
Example:
select AVG(Amount__C) from vyom_labs_sales__c
4. MIN(<colunmName>):
- This function returns smallest value of all values exist in specified column.
- This function can be used only with "numeric" and "Date" values.
- Specified column type should be "Number", "Currency", "Percent" and "Date" type.
Example:
select MIN(Amount__C) from vyom_labs_sales__c
5. MAX(<colunmName>):
- This function returns largest value of all values exist in specified column.
- This function can be used only with "numeric" and "Date" values.
- Specified column type should be "Number", "Currency", "Percent" and "Date" type
Example:
select MAX(Amount__C) from vyom_labs_sales__c
HAVING Clause:
- This clause is used to apply filter, after grouping, using "GROUP BY" clause.
- "HAVING" clause should be used along with "GROUP BY" clause.
- "WHERE" clause is used to apply filter before grouping, whereas, "HAVING"
clause is used to apply filter after grouping.
- "WHERE" and "HAVING", both clauses can be used in single SOQL query.
Example:
Conditional Expressions:
Conditional
Description Query
Operator
select Name,closedate from opportunity where
= Equals
name='New Opportunity created'
select Name,closedate from opportunity where name!
!= Not Equals ='New Opportunity created'Select salary__c from
employee__c where salary__c<=20000
Less Than, Less Than or Select salary__ c from employee__c where
< , <=
Equal To salary__c<=20000
Greater Than, Greater
> , >= Select salary__ from employee__c where salary>=20000
Than or Equal To
Select name, country__c, Student_skills__c from
Includes or Excludes
INCLUDES, Student__C where student_skills__C includes
Values. Applies only to
EXCLUDES (‘salesforce’)
Multi-Select Picklists.
Returns the records where
select Name,closedate from opportunity where name like
the field values match the
LIKE '%united%'
pattern specified after the
LIKE operator
Selects only the records
where the value of the
select FirstName,LastName from contact where
IN field matches any of the
FirstName in ('rose','sean')
values specified after IN
keyword
Selects only the records
where the value of the
select FirstName,LastName from contact where
NOT IN DOES NOT MATCH any
FirstName not in ('rose','sean')
of the values specified
after IN keyword
List<student__c> deletedstud = [select id, name from student__c where isDeleted = true ALL
ROWS];
system.debug(deletedstud);
Relationship Queries:
- By using relationship queries, we can fetch records from multiple objects which are associated
with each other by either "Lookup" association or "Master-Detail" association.
- By using relationship queries, we can reduce number of SOQL queries inside
an application.
- Approaches:
Example:
SELECT Name, (SELECT LastName FROM Contacts) FROM Account WHERE Name = 'SFDC
Computing'
- Upon fetching child object record, we can fetch its associated parent, even grandparent records
also.
- To fetch parent object record details, parent object field should be refenced with,
"ParentObjectName.fieldName".
- We can refer upto 10 reference objects in a single SOQL query.ie, upto 10th grandparent record
details.
Example:
select Name,Account.Name,Account.Type from Opportunity
Example:
select name,(select name,age__c,salary__c from employees__r) from department__c
DML Statements:
Insert Statement:
Syntax:
insert sObject
insert sObject[]
Example:
Update Statement:
update sObject[]
Example:
Delete Statement:
- By using "Delete" statement, we can delete one or multiple records from specified object.
- Upon deleting the records from an object, "Record ID" should be used.
- All deleted records are stored in "RecycleBin" for 15 days.
Syntax:
delete sObject
delete sObject[]
try{
delete deleteStudent;
}
catch(DmlException e){}
Undelete Statement:
- By using "Undelete" statement, we can bring back deleted records from "Recycle Bin" to actual
object.
- We can restore one or more records from "Recycle Bin" to actual object.
Syntax:
undelete sObject | ID
undelete sObject[] | ID
Example:
The following example undeletes an account named 'Universal Containers'. The ALL ROWS
keyword queries all rows for both top level and aggregate relationships, including deleted records
and archived activities.
undelete savedAccts;
system.debug(savedAccts);
Upsert Statement:
Syntax:
upsert sObject | sObject[]
upsert sObject | sObject[] field
Example:
Contact josh = new Contact(FirstName='Josh',LastName='Kaplan',Department='Finance');
insert josh;
upsert contacts;
Example:
Account[] acctsList = [SELECT Id, Name, BillingCity FROM Account WHERE BillingCity =
'Kolkata'];
for (Account a : acctsList){
a.BillingCity = 'Mumbai';
}
try {
upsert acctsList;
}
catch (DmlException e)
- When we try to perform more than 150 DML statements inside single transction,
then Salesforce aborts the operation and throw "Too many DML statements:
151" exception.
insert conList;
listToUpdate.add(con);
}
}
update listToUpdate;
1. Each DML statement is used implicit transaction by default, which allows to commit transaction
only if, all operations are completed successfully.If any operation gets failed, then entire transaction
gets rolled back.
2. There is no tracking mechanism to track which records got failed in DML transaction.
3. DML statements do not allow "Partial Processing" of records. ie, if any of record got failed, it
doesn't allow to process other remaining records.
Types of SOQL Queries:
- Query columns and condition are static. ie, upon preparing the query we hava to specify column
names and required condition. We cannot include columns or condition at runtime.
- All SOQL queries written inside Apex class, should be placed inside square brackets "[....]".
- All static SOQL queries will be executed automatically.
- If SOQL query returns only one record, then we need to store the result in the object of associated
type.
- If SOQL query returns multiple records, then we need to store the result in "List" collection of
associated type.
- By using dynamic SOQL query, we can prepare a query by adding columns and conditions at
runtime.
- Dynamic SOQL query must be stored in "String" variable, and once query is prepared,
we have to execute that query "manually".
- Dynamic SOQL query is executed manually, by using "Database.query(String ‘dynamicQuery’)
method.
- Dynamic SOQL query always returns "List" collection of associated type, though query return
single record.
- The variable passed as a parameter, must also be enclosed in single quotation mark.
Example:
Example:
public class DatabaseHandler {
public static void getContact(String searchText){
if(searchText!=NULL && searchText!=''){
string queryString='select Id,FirstName,LastName,Email from Contact';
}
}
else{
system.debug('search text is empty');
}
}
}
}
DatabaseHandler.getContact('Godrej Company');
Example:
public class Dynamic_SOQL{
Execution:
String query='select id,name from account';
Dynamic_SOQL.SOQLMethod(query);
Unlike DML statements, Database methods have an optional allOrNone parameter that allows you
to specify whether the operation should partially succeed. When this parameter is set to false, if
errors occur on a partial set of records, the successful records will be committed and errors will be
returned for the failed records. Also, no exceptions are thrown with the partial success option.
1) Database.insert():
- The second argument of this method is optional. If we dont provide second argument,or we
provide "TRUE" value, then this method works like normal DML statement.
- If we provide second argument value as "FALSE", then this method allows "Partial Processing" of
records.
- This method returns array of "Database.SaveResult" class. This class is used to track result of each
operation.
Example:
Example2:
Opportunity opp1 = new Opportunity(
Name='First Opportunity',
CloseDate=Date.today(),
Amount=7000,
StageName='Prospecting'
);
Opportunity opp2 = new Opportunity(
Name='New Opportunity1',
CloseDate=Date.today(),
Amount=6000,
StageName='Prospecting'
);
List<Opportunity> lsr=new List<Opportunity>{opp1,opp2};
Database.SaveResult[] sr=Database.insert(lsr,false);
- Methods of "Database.SaveResult" class:
1. Boolean isSuccess():This method returns "TRUE" if operation is completed successfully, else it
returns "FALSE".
2. ID getID():
This method returns "ID" of successfully inserted record.
3. Database.Error[] getErrors():
This method returns array of "Database.Error" class. This class is used to get error information,
that has been generated during insertion operation.
2) Database.update():
3) Database.delete():
4) Database.undelete():
- This method is used to undelete one or more records from "Recycle Bin" to actual object.
- Syntax:
5) Database.upsert():
- This method is updates a record if "Record ID" is exist, or it inserts new record.
- Syntax:
6) Database.emptyRecycleBin():
- This method is used to delete all records from "Recycle Bin" permanently.
- Syntax:
SOSL Statements:
Salesforce Object Search Language (SOSL) is a Salesforce search language that is used to perform
text searches in records. Use SOSL to search fields across multiple standard and custom object
records in Salesforce.
Example:
1) find {sfdc} in all fields returning Account(Name)
This is an example of a SOSL query that searches for accounts and contacts that have any fields
with the word 'SFDC'.
Adding SOSL queries to Apex is simple—you can embed SOSL queries directly in your Apex code.
When SOSL is embedded in Apex, it is referred to as inline SOSL.
SOSL statements evaluate to a list of lists of sObjects, where each list contains the search results for
a particular sObject type. The result lists are always returned in the same order as they were
specified in the SOSL query. If a SOSL query does not return any records for a specified sObject
type, the search results include an empty list for that sObject.
Example:
you can return a list of Account and leads that begins with sfdc.
For example, you can return a list of accounts, contacts, opportunities, and leads that begin with the
phrase map:
from searchlist, you can create arrays for each object returned: