What is SOQL?
- SOQL means Salesforce Object Query Language.
- It is used to query the data (or) retrieve the data.
- We can also retrieve corresponding parent/child records.
- It will return the result in the form of List<sobject> / map<id, sobject>.
- SOQL can return 50,000 records at max.
QUERY :- Query is a statement written to retrieve the data.
Example :- Select fields from sobject where condition.
Syntax for SOQL :
Select <fieldnames> from <Object Name>
- WHERE <condition>
- GROUP BY<Column names>
- HAVING <conditions>
- ORDER BY <column names>[ORDER BY Name ASC or DESC]
- FOR UPDATE (to lock the records getting updated by from other transactions).
- LIMIT<No of records to return>
- OFFSET <Number of records to skip>
- ALL ROWS (fetch all records from sobject including which are deleted in last 15days).
LIMIT followed by OFFSET.
1. Write a SOQL to fetch all the account records with Name,Industry fields?
List<Account> acc = [select id, Name, Industry from Account];
SOQL query can be executed in four formats in Apex.
- List< sobject> result = [query statement];
- list<sobject> result = database.query(query statement);
- database.QueryLocator result = database.getQueryLocator(query statement);
- map<id, sobject> result = new map<id, sobject>([query statement]);
Salesforce Object Search Language (SOSL)
SOSL is to search your organization’s Salesforce data.
When to Use SOQL?
Use SOQL when you know which objects the data resides in, and you want to:
- Retrieve data from a single object or from multiple objects that are related to one another.
- Count the number of records that meet specified criteria.
- Sort results as part of the query.
- Retrieve data from number, date, or checkbox fields.
This is an example of a SOSL query that searches for accounts and contacts that have any fields with the word ‘SFDC’.
List<List<SObject>> searchList = [FIND ‘SFDC’ IN ALL FIELDS RETURNING Account(Name), Contact(FirstName,LastName)];