Documente Academic
Documente Profesional
Documente Cultură
1.SOQL :
c. Soql's are used to fetch the data from the sobjecs(Standard or Custom objects)
.
d. Using soql we can also fetch data from related objects (child or parent
records)
using relation fields
syntax :
2. Query : This is the statement writen to fetch the records from the database based
on the business requirement
Query Example :
1.Write a soql to fetch all the account records with name,Insutry fields .
2.Write a soql to Fetch all the contact records with lastname,firstname fields
4.Write a soql query to fetch all user records with lastname,firstname, profile
userName
|--------Developer Console
|--------Panel
|-----Debug
|-----Open Annonymous window
1. Write Query
2. Execute the query
3. See the result in the log file
UserName
|--------Developer Console
|-------Expand the Console
|------select Query Editor
3. From the result we can perform update, create , delete ,save ,Edit Detail
page
operation on the selected records
Note: Query editor is not for applying business logic it is used only for
manual
operatons on the result set .
8. Workbench : Workbench is a third party used to test the data or perform apex
logics
and testing webservices
Page 3
SOQL-ClassRoom-Notes-
3. Choose the api version
8.Execute
10..Static Query :
are fixed and know to us then we make single query statement which will run
throughout the business operation are called static query
Ex : String accIndustry='banking';
if(accIndustry== 'Energy'){
query= query+'where Industry=\'Energy\' ';
}
else{
query=query+' where phone=\'123\' ';
}
List<Account> result=Database.query(query);
====================================================================================
=
Examples :
====================================================================================
==
Example 1:
Write a soql to fetch name,industry ,phone from Accoutn and display it in the VF
page
Example :
public SoqlExample1(){
VFPage :
<apex:page controller="SoqlExample1">
<apex:form>
<apex:pageBlock title="SoqlExample">
<apex:pageBlockTable value="{!accs}" var="a">
<apex:column value="{!a.name}" />
<apex:column value="{!a.industry}" />
<apex:column value="{!a.phone}" />
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>
Example 2:
Page 5
SOQL-ClassRoom-Notes-
Write the soql query to fetch data from opportunity object and display in the VF
page
VF page :
<apex:page controller="SoqlExample2">
<apex:form>
<apex:pageBlock title="SoqlExample">
<apex:pageBlockTable value="{!optyList}" var="a">
<apex:column value="{!a.name}" />
<apex:column value="{!a.stageName}" />
<apex:column value="{!a.amount}" />
<apex:column value="{!a.closeDate}" />
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>
====================================================================================
===
12. Limit :
Syntax:
Limit <Number Of Rows Returned>
Ex:
Limit 1
Limit 10
Limit 50
13. Offset :
Syntax :
offsett <RowNumber>
offset 1
offset 10
offset 1000
Ex: write soql to fetch all the accounts from 10th records
Note : if you taking limit and offset together we have use limit followed by offset
14.Order By :
Syntax :
Example :
Ex: Write a soql to fetch all the account records in the accending order of
accountName
Ex : Write a soql to fetch all the account records in the decending order of
industry
Ex: Write the soql to fetch last 10 opportunity records based on created
date
All Rows clause used to fetch all the records from sobject including the
records
which are deleted in the last 15 days .
Ex:Write a soql to fetch all the records including records which are in
recylce bin from Accoutn sobject
Ex: Write a soql to fetch all the records including recycle bin from case
Page 8
SOQL-ClassRoom-Notes-
====================================================================================
====
Examples :
====================================================================================
====
Example 1:
Example :
Visualforce :
<apex:page controller="SoqlExample1">
Page 9
SOQL-ClassRoom-Notes-
<apex:form>
<apex:pageBlock title="SOQLExample">
<apex:pageBlockButtons location="top">
<apex:commandButton value="Limit" action="{!setLimit}" />
<apex:commandButton value="Offset" action="{!setOffset}" />
<apex:commandButton value="LimitOffset" action="{!LimitOffset}" />
<apex:commandButton value="SortAscending" action="{!sortAsc}" />
<apex:commandButton value="SortDesc" action="{!sortDesc}" />
<apex:commandButton value="ALLROWS" action="{!fetchAll}" />
</apex:pageBlockButtons>
<apex:pageBlockTable value="{!result}" var="a">
<apex:column value="{!a.name}" />
<apex:column value="{!a.industry}" />
<apex:column value="{!a.phone}" />
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>
Example 2 :
1. Write a soql query to fetch last ten opportunity records based on closed date
Solution :
VF Page :
<apex:page controller="SoqlExample3">
<apex:pageBlock title="Opporunity">
<apex:pageBlockTable value="{!optyList}" var="a">
<apex:column value="{!a.stageName}"/>
<apex:column value="{!a.closeDate}" />
<apex:column value="{!a.amount}" />
</apex:pageBlockTable>
</apex:pageBlock>
</apex:page>
Page 10
SOQL-ClassRoom-Notes-
====================================================================================
====
Excercise :
====================================================================================
====
1. Write a soql to fetch first 5 Accounts based on created date and display in the
VF
page
2. Write a soql query to fetch last 20 records opportunity records based on closed
date
and display in the vF page
3. Fetch all the case records and display first 10 case records based on createdate
and display in the VF page
====================================================================================
=====
Syntax :
Single Condition :
Mulitple Conditions :
Example :
Where name='satish';
Example :
1.Write a soql to fetch all the account records whose industry is banking
Page 11
SOQL-ClassRoom-Notes-
List<Account> accs= [select name,industry ,phone from Account where
industry='banking'];
2. Write a soql to fetch all the case records whose origin is email
3.Write soql to fetch the all opprotunties whose stage name is 'closed won' and
amount is more than 50000
String empName='satish';
Where name=:empName;
====================================================================================
====
Example :
VF page :
<apex:page controller="SoqlExample2">
<apex:form>
<apex:pageBlock title="Opportunity">
<apex:pageBlockButtons location="top">
<apex:commandButton value="Static" action="{!staticWhere}" />
<apex:commandButton value="Dynamic" action="{!dynamicWhere}" />
</apex:pageBlockButtons>
<apex:pageBlockTable value="{!optyList}" var="a">
<apex:column value="{!a.name}" />
<apex:column value="{!a.amount}" />
<apex:column value="{!a.stageName}" />
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>
Example 2:
VF page :
<apex:page controller="SoqlExample5">
<apex:form>
<apex:pageBlock title="SoqlExample">
Enter name : <apex:inputText value="{!accName}" /> <br/><br/>
Enter Industry: <apex:inputText value="{!accIndustry}" /><br/><br/>
Page 13
SOQL-ClassRoom-Notes-
<apex:commandButton value="Single" action="{!single}" />
<apex:commandButton value="Multiple" action="{!multiple}" />
</apex:pageBlock>
<apex:pageBlock title="Opporunity">
<apex:pageBlockTable value="{!accs}" var="a">
<apex:column value="{!a.Name}"/>
<apex:column value="{!a.industry}" />
<apex:column value="{!a.phone}" />
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>
====================================================================================
===
17.In clause :When we want to comapare
Syntax
Ex : Write soql query to fetch all the account records whose industry is Banking or
enery or Education.
'Energy','Education') ];
Ex: Write a soql to fetch all the lead records whose leadSource is email,phone, web;
: Write a soql to fetch all the account records whose names are in above list of
names
Example :
public class SOQLExample3 {
public List<Account> accs {set;get;}
public SOQLExample3(){
accs=[select name,industry,phone from Account];
}
public void staticIn(){
accs=[select name,Industry,phone from Account where Industry IN
('Banking','Energy')];
}
public void dynamicIn(){
List<string> myList=new List<String>{'Banking','Education'};
accs=[select name,Industry,phone from Account where Industry In :myList];
}
public void soqlIn(){
List<Account> myData=[select id ,name from Account where Industry='Energy'];
accs=[select name,industry,phone from Account where Id IN: mydata and
Rating='warm'];
}
}
<apex:page controller="SOQLExample3">
<apex:form>
<apex:pageBlock title="Account">
<apex:pageBlockButtons>
<apex:commandButton value="StaticIn" action="{!staticin}" />
<apex:commandButton value="DynamicIn" action="{!dynamicIn}" />
<apex:commandButton value="SoqlIn" action="{!soqlIn}" />
</apex:pageBlockButtons>
<apex:pageBlockTable value="{!accs}" var="a">
<apex:column value="{!a.name}" />
<apex:column value="{!a.industry}" />
<apex:column value="{!a.phone}" />
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>
====================================================================================
===
Task1 : Fetch all the opportunity records whose account is industry is energy ;
Task 2: Write soql query to fetch all the case records whose priority is Normal or
High
Task 3: Write soql query to fetch all the cases of those accounts whose rating is
Hot.
[select subject,Priority from Case where AccountId In ([select id from Account where
rating='HOT']) ];
====================================================================================
====
18 .FOR UPDATE :
For Update clause will lock the records from getting updated by from other
transactions
untill the current transaction is completed
Like clause is used to compare the string values or search for string value in the
given fields
'%' --Any
LIKE '_k_r%' : Any string which contains second character as k and fourth
as r
Example :
1.Write a soql query to fetch all the Contact records whose lastname ends with s .
2.Write a soql query to fetch all the Opportunity records whose opportunity name
contains
'salesforce'
1. TODAY :
2.Yesterday
3.THIS_WEEk
4.NEXT_Week
5.LAST_WEEK
6.THIS_MONTH
7.NEXT_MONTH
Page 17
SOQL-ClassRoom-Notes-
8.LAST_MONTH
9.THIS_YEAR
10.NEXT_YEAR
11.LAST_N_WEEKS :n
12.NEXT_N_WEEKS : n
13.LAST_N_DAYS : n
14.NEXT_N_DAYS: n
Example :
1. Write a soql to fetch all the account records created in the last year
2. Write soql to fetch all the opportunity records which are going to closed in next
15 days
3. Write a soql to fetch all the application records which are Approved in last
week
1.Object :Application
====================================================================================
====
21. Date andTime methods :
DAY_IN_WEEK() Returns a number representing the day of the week for a date
field.
Ex: 1 for Sunday
Ex: 7 for Saturday
DAY_IN_YEAR() Returns a number representing the day in the year for a date field.
Ex:
32 for February 1
====================================================================================
====
Parent -to-child--Soql :
If two objects are connected using a lookup or master-detail relation then we can
use
parent-to-child-soql query to fetch list of child records along with every parent.
Ex:
-----------
| |
|
Page 19
SOQL-ClassRoom-Notes-
|
|
-------------
-----------------------------------------------------------------------------------
1. Parent is Stamdard object and Child is Standard object
------------------------------------------------------------------------------------
Syntax :
Parent];
Account];
Account];
------------------------------------------------------------------------------------
-
Page 20
SOQL-ClassRoom-Notes-
Parent is a standard object and Custom object is a child
------------------------------------------------------------------------------------
-
Syntax :
from Parent];
Note : At the time of creating a lookup /master -detail field We have a field called
ChildRelationName ..What ever the name we give in this box that will be used as
Ex: Account and Customer (Custom object) are connected by lookup relation with
Child relation name 'Customers' .
Ex: Contact and Loan object are connected by Lookup relation and childRelation name
is Loans then we
Ex: Account and Loan are connected by Child Relation Name MyLoan
from Account];
Note : generally child object name will be the child relation name
------------------------------------------------------------------------------------
---
Custom Object is the parent and standard object is the child
------------------------------------------------------------------------------------
Page 21
SOQL-ClassRoom-Notes-
----
Syntax :
Ex: Account has lookup relation with Customer with Customer as parent and
chilrelation
name as 'Accounts'
------------------------------------------------------------------------------------
-
Custom Object as parent and Custom object as child
------------------------------------------------------------------------------------
--
Syntax :
Ex: CreditCard abd Payment objects are connected by Master-Detail relation with
child relation name as 'Payments'
Ex : Fetch all the Account records with list of corresponding contacts and
Page 22
SOQL-ClassRoom-Notes-
for(Account a: accs){
for(Contact c:a.contacts){
c.otherPhone=a.phone;
cons.add(c);
Scenario :2
Create a map with accountName as key and sum of corresponding child opportuntiy
amount as value of map. and insert the values.
/* Write a parent child soql to fetch all the account records with */
/* corresponding child Opportunites */
for(Account a: accs){
Decimal amount=0;
/* Every account has list of opportunities so fetch the list of opportunties for
account a by using a.opportunities
for(Opportunity op :a.opportunities){
amount=amount+op.amount;
}
accMap.put(a.name,amount);
Page 23
SOQL-ClassRoom-Notes-
}
====================================================================================
=====
Child to Parent Soql query :
====================================================================================
=====
objectS)
Syntaxt
Ex: Contact and Account are connected by using Standard Lookup field Account
Ex: Customer and user object are connected by using Standard Lookup field CreatedBy
from Customer__c];
------------------------------------------------------------------------------------
----
3. Relation field is created by user i.e both the objects are connected by Custom
field
------------------------------------------------------------------------------------
---
Page 24
SOQL-ClassRoom-Notes-
Syntax :
List<Contact> cons=[select
Lastname,firstname,MyAccount__r.Name,MyAccount__r.Industry
from Contact];
Ex:Payment object has master-detail relation with Creditcard with the field name
CreditCard
List<Payment__c> result=[select
Mode__c,Amount__c,Creditcard__r.Type__c,CreditCard__r.Limit__c from Payment__c];
====================================================================================
===
AggregateFunctions :
Ex : Find count how many account records are there in the sobject Account
Ex: Find the count of no of Opportunities which are won in this month
CloseDate=THIS_MONTH];
2. SUM(Field) : This will give you summarized value of the give field from the
QueryResult
Decimal amount=(Decimal)result.get('expr0');
Decimal amount=(Decimal)result.get('total');
3.AVG(field) : This will return avg value of the given field from query result
4.MIN(FieldName): This will return minimum value of the given field from query
result
5.MAX(Field Name) : This will return maximum value of the given field from query
result
Example :1
Decimal total=(Decimal)result.get('total');
Decimal avgval=(Decimal)result.get('avgval');
Decimal maxval=(Decimal)result.get('maxval');
Decimal minval=(Decimal)result.get('minval');
System.debug('Total :'+total);
System.debug('Avg :'+avgval);
System.debug('MIN :'+minval);
System.debug('Max :'+maxval);
Group By : if we use group by clause along with Aggregate functions we get the
result as
List<AggregateResult>
: we can only query the fields which are part of aggregare result or group
by clause .
Page 26
SOQL-ClassRoom-Notes-
String stageName=(String)result.get('stagename');
Decimal total=(Decimal)result.get('total');
Decimal avgval=(Decimal)result.get('avgval');
Decimal maxval=(Decimal)result.get('maxval');
Decimal minval=(Decimal)result.get('minval');
System.debug('====Start ====');
System.debug('StageName:'+stageName);
System.debug('Total :'+total);
System.debug('Avg :'+avgval);
System.debug('MIN :'+minval);
System.debug('Max :'+maxval);
}
Page 27