SOQL Queries
SOQL Queries
=============
SOQL --> Salesforce Object Query Language
Query --> Database.com --> Fetch the Records --> Salesforce Objects
By using SOQL Queries, we can fetch one / more records from One / more objects from
the Database.com.
We can add one / more user defined conditions to be used to filter the records from
the resultset.
Syntax:
SELECT <FieldNames / APINames> FROM <ObjectName>
[ WHERE <Conditions> ]
[ GROUP BY <ColumnNames> ]
[ HAVING <Conditions> ]
[ ORDER BY <ColumnNames> ]
[ LIMIT <Number Of Records to Return> ]
[ OFFSET <Number of Records to Skip> ]
[ FOR UPDATE ]
[ ALL ROWS ]
Governor Limits:
================
1. We can have max. of 100 SOQL Queries per Transaction.
When the user tries use more than 100 SOQL Queries, then Salesforce
will raise an exception "System.Limit Exception. Too Many SOQL Queries : 101".
Best Practices:
===============
1. We should not Write any SOQL Queries inside the "FOR Loop". Always avoid
the usage of SOQL Queries inside the FOR Loop.
2. Don't fetch the unnecessary fields information from the object. So that we
can occupy the less memory and we can make the application performance improved.
// Write an SOQL Query to fetch the Account ID, Name, Rating, Industry and
AnnualRevenue
fields information from the object.
// Write an SOQL Query, to fetch all the Contact Records from the object.
// Write an SOQL Query, to fetch all the User Records from the object.
Select id, firstname, lastname, email, username, title, isActive from user
// Write an SOQL Query, to fetch all the Email Templates from the object.
// Write an SOQL Query, to fetch all the Hiring Manager Records from the object.
// Write an SOQL Query, to fetch all the Position Records from the object.
Note:
We can invoke the SOQL Queries by using Apex Programming also.
2 Types.
In Static SOQL Queries, We can't Add the Columns and Conditions to the Query
at runtime. It's a Fixed Query.
Static SOQL Queries should be always enclosed inside the "Square Braces".
Syntax:
[ SOQL Query ]
Ex:
[ Select id, name, rating, industry from Account ]
Ex:
Account acc = [ Select id, name, rating, industry from Account ];
if(acc != null)
{
System.debug('Account Id is...: '+ acc.id);
system.debug('Account Name is....: '+ acc.Name);
system.debug('Account Rating is...: '+ acc.rating);
system.debug('Annual Revenue is...: '+ acc.annualrevenue);
}
Ex:
Hiring_Manager__C hr = [Select id, Name, Location__C, Contact_number__C
from
Hiring_Manager__C];
if(hr != null)
{
system.debug('Hiring Manager ID is...: '+ hr.id);
system.debug('HR Name is....: '+ hr.name);
system.debug('Contact Number is...: '+ hr.contact_Number__C);
system.debug('Email Id is....: '+ hr.email_id__C);
}
Syntax:
List<SObjectDatatype> <objectName> = [SOQL Query];
Ex:
List<Lead> lstLeads = [Select id, firstname, lastname, email, title, phone,
fax
from Lead];
if(! lstLeads.isEmpty())
{
for(Lead ld : lstLeads)
{
system.debug('Lead ID is...: '+ ld.id);
system.debug('Lead Name is...: '+ ld.firstname + ' '+
ld.lastname);
system.debug('Lead Email Id is...: '+ ld.email);
}
}
UseCase:
========
Write an apex program, to fetch all the Account Records from the object and
will represent on the debug log file.
Class Code:
-----------
public class DatabaseHelper
{
Public static void GetAllAccountRecords()
{
List<Account> lstAccounts = [Select id, name, rating, industry,
annualrevenue,
phone, fax, active__C
from
Account];
if(! lstAccounts.isEmpty())
{
for(Account acc : lstAccounts)
{
system.debug('Account Id is...: ' + acc.id);
system.debug('Account Name is...: '+ acc.Name);
system.debug('Rating Value is...: '+ acc.Rating);
system.debug('Industry Name is...: '+ acc.Industry);
system.debug('Annual Revenue is...: '+ acc.AnnualRevenue);
system.debug('Contact Number is...: '+ acc.Phone);
system.debug('Active Status is...: '+ acc.Active__c);
system.debug('--------------------------------------------');
}
}
}
}
Execution:
----------
DatabaseHelper.GetAllAccountRecords();
UseCase:
========
Write an apex program, to fetch all the Case Records from the object and
represent on the Debug Log File.
Class Code:
-----------
public class DatabaseHelper
{
Public static void GetAllCaseRecords()
{
for(Case cs : [Select id, casenumber, status, priority, origin, type,
reason, subject from Case])
{
system.debug('Case Number is...: '+ cs.CaseNumber);
system.debug('Case Status is...: '+ cs.Status);
system.debug('Case Priority.....: '+ cs.Priority);
system.debug('Case origin......: '+ cs.Origin);
system.debug('Case Reason is....: ' +cs.Reason);
system.debug('Case Subject is....:' + cs.Subject);
system.debug('---------------------------------------');
}
}
}
Execution:
----------
DatabaseHelper.GetAllCaseRecords();
UseCase:
========
Write an apex program, to fetch all the Hiring Manager Records from the
object and represent on the Debug Log File, by storing the records in the Map
Collection.
Class Code:
-----------
public class DatabaseHelper
{
Public static void GetAllHRRecords()
{
/*
List<Hiring_Manager__C> lstHrs = [Select id, name, location__C,
Contact_Number__C, email_id__C
from Hiring_Manager__C];
if(! lstHrs.isEmpty())
{
for(Hiring_Manager__C hr : lstHrs)
{
mapHRRecords.Put(hr.Id, hr);
}
}
*/
from Hiring_Manager__c]);
if(! mapHRRecords.isEmpty())
{
for(Hiring_Manager__C hr : mapHRRecords.Values())
{
system.debug('Hiring Manager Record is..: '+ hr);
}
}
}
}
Execution:
----------
DatabaseHelper.GetAllHRRecords();
Assignments:
============
1. Write an apex program, to fetch all the Contact Records from the object
and represent the records on the Debug Log File.
2. Write an apex program, to fetch all the Opportunity Records from the
object and represent on the Debug Log File.
3. Write an apex program, to fetch all the User Records from the object and
store them into the "Map Collection" and Display the Records on the Debug Log File.
4. Write an apex program, to fetch all the Position Records from the object
and store them to the Map Collection. And represent the records on the Debug Log
File.
Limit Clause:
=============
Syntax:
[ SOQL Query
Limit <Integer> ]
Ex:
[SOQL Query
Limit 1]
Limit 5
Limit 10
Limit 25
UseCase:
========
Write an apex program, to fetch only 5 Case Records from the object.
Class Code:
-----------
public class DatabaseHelper
{
Public static void GetCaseRecords()
{
List<Case> lstCases = [Select id, casenumber, status, priority, type,
reason, subject from Case Limit 5];
for(Case cs : lstCases)
{
system.debug('Case Record is...: '+ cs);
}
}
}
Execution:
----------
DatabaseHelper.GetCaseRecords();
// Write an SOQL Query, to fetch 10 Hiring Manager Records from the object.
from Hiring_Manager__C
Limit 10];
// Write an SOQL Query to fetch 2 Email Templates from the object.
Limit 2];
// Write an SOQL Query, to fetch only one User Record from the object.
ALL ROWS:
=========
Syntax:
[SOQL Query
ALL ROWS]
UseCase:
========
Write an apex program, to fetch all the Account Records from the object,
including Deleted Records.
Class Code:
------------
public class DatabaseHelper
{
Public static void ExportAllAccounts()
{
for(Account acc : [Select id, name, rating, industry, annualrevenue,
active__C, isDeleted
from Account
ALL ROWS])
{
system.debug('Account Record is...: '+ acc);
}
}
}
Execution:
----------
DatabaseHelper.ExportAllAccounts();
ORDER BY Clause:
================
Syntax:
[SOQL Query
ORDER BY <ColumnName> [ASC(Default) / DESC] ]
UseCase:
========
Write an apex program, to fetch all the Account Records from the object and
arrange the records in Alphabetical Order based on the Name.
Class Code:
-----------
public class DatabaseHelper
{
Public static void GetSortedAccountsByName()
{
List<Account> lstAccounts = [Select id, name, rating, industry,
annualrevenue, active__C
from Account
Order by name
desc];
Execution:
----------
DatabaseHelper.GetSortedAccountsByName();
/*
Write an SOQL Query, to fetch all the User Records and Arrange them in
Alphabetical Order based
on UserName field.
*/
List<User> lstUSers = [Select id, firstname, lastname, company, email,
username, isActive
from User
Order by username];
/*
Write an SOQL Query to fetch top 5 Highest Amount Opportunity Records.
*/
List<Opportunity> lstOppty = [Select id, name, closedate, amount, stagename
from Opportunity
Order by amount desc
Limit 5];
/*
Write an SOQL Query to fetch the recently posted 3 Position Records.
*/
List<Position__C> lstPositions = [Select id, name, location__C,
position_status__C,
open_date__C,
milestone_date__C, createddate
from Position__C
Order by
CreatedDate desc
Limit 3];
FOR UPDATE:
===========
Syntax:
[SOQL Query
FOR UPDATE]
Ex:
List<Contact> lstContacts = [Select id, firstname, lastname, email, title,
phone,
fax, mailingCity,
mailingCountry
from Contact
FOR
UPDATE];
OFFSET Clause:
==============
This clause is used to specify the Number of Records to be get Skipped from the
ResultSet.
Syntax:
[SOQL Query
OFFSET <Integer> ]
Ex:
OFFSET 10
OFFSET 5
OFFSET 20
Ex:
OFFSET :<ParameterName>
Note:
Both Limit Clause and OFFSET Clause will be used to achieve the Pagination.
Where "Limit Clause" value should be always "Fixed". And Offset clause value will
be keep on changing upon click on the "Navigation Buttons".
Note:
Always OFFSET Clause should be followed by the "LIMIT Clause".
UseCase:
========
Write an apex program, to fetch the Accounts from the object based on the
specified OFFSET and Limit Values.
Class Code:
-----------
public class DatabaseHelper
{
Public static void GetAccounts(integer limitValue, integer offsetValue)
{
List<Account> lstAccounts = [Select id, name, rating, industry,
annualrevenue, active__C
from Account
Order by name
Limit : limitValue
Offset :
offsetValue];
if(! lstAccounts.isEmpty())
{
for(Account acc : lstAccounts)
{
system.debug('Account Record...: '+ acc);
}
}
}
}
Execution:
----------
DatabaseHelper.GetAccounts(50, 10);
DatabaseHelper.GetAccounts(50, 5);
DatabaseHelper.GetAccounts(50, 15);
WHERE Clause:
=============
Syntax:
[SOQL Query
WHERE <Conditions> ]
Ex:
Where Rating = 'Hot'
Where Industry = 'Banking'
Where AnnualRevenue >= 2500000
Where Location__C = 'Hyderabad'
Where Priority = 'High'
Where Email != Null
UseCase:
========
Write an apex program, to fetch all the Hiring Manager Records, who are
associated with "Bangalore Location".
Class Code:
-----------
public class DatabaseHelper
{
Public static void GetBangloreHRRecords()
{
List<Hiring_Manager__C> lstHrs = [Select id, name, Location__C,
Contact_Number__C, Email_id__C
from
Hiring_MAnager__C
Where
Location__C = 'Bangalore'];
if(! lstHrs.isEmpty())
{
for(Hiring_Manager__C hr : lstHrs)
{
system.debug('Hiring Manager Record...: '+ hr);
}
}
}
}
Execution:
----------
DatabaseHelper.GetBangloreHRRecords();
/*
Write an SOQL Query to fetch all the Banking Account Records from the object.
*/
List<Account> lstAccounts = [Select id, name, rating, industry,
annualrevenue, active__C
from Account
Where Industry = 'Banking'];
/*
Write an SOQL Query to fetch all the Case Records whose Priority is "High"
and Status is "New".
*/
List<Case> lstCases = [Select id, casenumber, status, priority, origin, type,
reason
from Case
Where Priority = 'High'
and Status = 'New'];
/*
Write an apex program, to fetch only the Deleted Account Records from the
Account object.
*/
List<Account> lstDeletedAccounts = [Select id, name, rating, industry,
isDeleted
from Account
Where isDeleted = true
ALL ROWS ];
/*
Write an SOQL Query, to fetch all the Active User Records.
*/
List<User> lstActiveUsers = [Select id, firstname, lastname, email, username,
isActive
from User
Where isActive = true];
Note:
Upon preparing the SOQL Query, we can supply the values to the Clauses to
prepare the conditions dynamically at runtime.
Syntax:
Where <FieldName> <operator> <Value>
Ex:
String ratingValue = 'Hot';
Where rating =: ratingValue;
UseCase:
========
Write an apex program, to fetch all the Case Records based on the specified
"Priority".
Class Code:
-----------
public class DatabaseHelper
{
Public static void GetCassesByPriority(string casePriority)
{
if(casePriority != null && casePriority != '')
{
for(Case csRecord : [Select id, casenumber, priority, status, type,
origin
from Case
Where priority =:
casePriority])
{
system.debug('Case Record is...: '+ csRecord);
}
}
}
}
Execution:
----------
DatabaseHelper.GetCassesByPriority('Low');
DatabaseHelper.GetCassesByPriority('High');
Assignments:
============
1. Write an Apex program, to fetch all the Account Records based on the
specified "Industry" at runtime.
2. Write an apex program, to fetch all the Position Records based on the
specified position Status.
3. Write an apex program, to fetch the User Record based on the Specified
User Name.
4. Write an apex program, to fetch all the Opportunity Records based on the
specified StageName.
Step 1: Dynamic SOQL Query should be always stored inside a "String Variable".
Syntax:
string <variableName> = 'SOQL Query';
Ex:
string accountsQuery = 'Select id, name, rating, industry,
annualrevenue from
account';
Ex:
List<Account> lstAccounts = Database.Query(accountsQuery);
UseCase:
========
Write an apex program, to search for the Lead Records based on the specified
input supplied by the user at runtime.
1. If the Input value is a string, then Search the Leads based on "Last
Name".
2. If the Input value is an Email, then Search the Leads based on the
"Email Field".
Class Code:
-----------
public class DatabaseHelper
{
Public static void SearchLeadRecords(string searchText)
{
if(searchText != null && searchText != '')
{
string leadRecordsQuery = 'Select id, firstname, lastname, email,
phone, fax from Lead ';
if(Pattern.matches('^[a-zA-Z0-9._|\\\\%#~`=?&/$^*!}{+-]+@[a-zA-Z0-9.-]
+\\.[a-zA-Z]{2,4}$', searchText))
{
system.debug('Input Value is an Email ID.');
leadRecordsQuery += 'Where email =: searchText';
}
else
{
system.debug('Input Value is a String.');
leadRecordsQuery += ' Where lastname =: searchText';
}
for(Lead ld : lstLEads)
{
system.debug('Lead Record is...: '+ ld);
}
}
}
}
Execution:
----------
DatabaseHelper.SearchLeadRecords('[email protected]');
IN Operator:
============
Select id, name, rating, industry, annualrevenue, active__C, phone, fax
from Account
Where industry = 'Banking' OR
Industry = 'Finance' OR
Industry = 'Manufacturing' OR
Industry = 'Education' OR
Industry = 'Insurance' OR
Industry = 'Consulting'
(OR)
(OR)
(OR)
(OR)
Account Records:
Account2 Finance
|
--> Contact 1
Acocunt4 Education
UseCase:
========
Write an apex program, to fetch all the Contact Records associated with the
"Banking Accounts".
Class Code:
-----------
public class DatabaseHelper
{
Public static void GetBankingContacts()
{
// Get the Banking Account Records with ID's.
Map<ID, Account> mapAccounts = new Map<ID,Account>([Select id, name,
industry
from Account
Where
industry = 'Banking']);
if(! mapAccounts.isEmpty())
{
for(Contact con : [Select id, firstname, lastname, email, title, phone,
fax, accountid
from Contact
Where accountid IN :
mapAccounts.KeySet() ])
{
system.debug('Contact Record is...: '+ con);
}
}
}
}
Execution:
----------
DatabaseHelper.GetBankingContacts();
LIKE Operator:
==============
By using LIKE operator, we can fetch the similar kind of information from the
object.
Note:
LIKE operator should be always used along with the "WHERE Clause".
Syntax:
[SOQL Query
Where <ColumnName> LIKE '<Expression>']
Ex:
Returns the Records Whose Name is Starting with "R".
Where Name Like 'R%' --> Rajesh, Ramesh, Rakesh, Raja,...etc.
UseCase:
========
Write an apex program, to fetch all the Similar Kind of Account Record based
on the name columns by using the LIKE operator.
Class Code:
-----------
public class DatabaseHelper
{
Public static void SearchAccounts(string searchText)
{
if(searchText != null && searchText != '')
{
searchText += '%';
Execution:
----------
DatabaseHelper.SearchAccounts('G');
/*
Write an SOQL Query to fetch all the Lead Records whose Last Name starting
with the word "kumar".
*/
/*
Write an SOQL Query to fetch all the Contact Records, whose Mailing Street
Contains the word "pally".
*/
/*
Write an SOQL Query to fetch all the Positions, whose name ends with
"Architect".
*/
/*
Write an apex program, to fetch the Records Count in the object.
*/
Class Code:
-----------
public class DatabaseHelper
{
Public static void GetRecordsCount()
{
// Static SOQL Query.
integer recordsCount = [Select count() from Account];
system.debug('Account Records Count....: '+ recordsCount);
Execution:
----------
DatabaseHelper.GetRecordsCount();