Nripesh Kumar Joshi (Salesforce Developer)
Some SOQL Query Examples in Salesforce (Part 1)
1. Fetch the child record from parent record (Contact is child and Account is Parent) –
Standard Objects
SELECT Id, Name, (SELECT Id, LastName FROM Contacts) FROM Account.
Note- Contacts is a Child Relationship Name which is lookup field in child object
2. Fetch the child record from parent record (Student__c is child and Teacher__c is
Parent) – Custom Objects
SELECT Id, Name, (SELECT Id, Name FROM Students__r) FROM Teacher__c
Note - Students is a Child Relationship Name(appended ‘ __r’ in Students) which is lookup field in
child object
3. Fetch the Parent record from Child Record (Contact is child and Account is Parent) –
Standard Object
SELECT Id, Account.Name FROM Contact
4. Fetch the Parent record from Child Record (Student__c is child and Teacher__c is Parent) –
Custom Object
SELECT Id, Teacher__r.Name FROM Student__c
Note- Here we don’t need to add s in Relationship
5. Fetch the Account that has no contact record
SELECT Id, Name FROM Account WHERE Id NOT IN (SELECT AccountId FROM Contact)
Nripesh Kumar Joshi (Salesforce Developer)
Note- AccountId(Id of Account that is associated with contact) is lookup field
6. Fetch the Latest Account Record
SELECT Id, Name,CreatedDate FROM Account ORDER BY CreatedDate DESC
7. Fetch theAccount record which is group by Name
SELECT Count(Id), Name FROM Account GROUP BY Name
Note- We can not use count with the field that is used in Group By.
For example we can not count name because we are using Name field in Group By
8. Determine how many leads are associated with each LeadSource value
SELECT LeadSource, COUNT(Name) FROM Lead GROUP BY LeadSource
9. Fetch the Lead Record that are associate with each LeadSource that generated more
than 10 times
SELECT LeadSource, COUNT(Name) FROM Lead GROUP BY LeadSource Having Count(Name)>10
10. Fetch the Lead record where name end with ‘abc’
SELECT LeadSource, Name FROM Lead WHERE Name LIKE '%abc’
Some Clauses in SOQL Query
In the above Queries we have used many clauses.
*** NOT - NOT keyword is used for negation.
Nripesh Kumar Joshi (Salesforce Developer)
*** Group By - GROUP BY is used with Aggregate functions to group the result set by single or
multiple columns.
*** Order By - ORDER BY is used to sort the records in ascending(ASC) or descending(DESC)
order. It is used after the WHERE clause.
*** Like - LIKE keyword allows selective queries using wildcards.
*** Having - HAVING is an optional clause that can be used in a SOQL query to filter results that
aggregate functions return.
*** WHERE - We can add the condition with the help of WHERE Clause
Governor Limit for SOQL
Description Synchronous Limit Asynchronous Limit
Total number of SOQL queries issued 1 100 200
Total number of records retrieved by SOQL 50,000 50,000
queries