SlideShare a Scribd company logo
Force.com Apex Advanced 
Sujit Kumar 
Zenolocity LLC © 2012 - 2024
Overview 
• Aggregate SOQL Features 
• Additional SOQL Features 
• SOSL 
• Transaction Processing 
• Managed Sharing 
• Send & Receive Email 
• Dynamic Apex 
• Patterns and Matchers 
• Custom Settings in Apex 
• System class and methods
Aggregate Functions 
• AVG, COUNT, COUNT_DISTINCT, MIN, MAX, 
SUM. 
• AVG, SUM : Operate on Numeric Fields only. 
• COUNT, COUNT_DISTINCT, MIN, MAX: 
Numeric, Date, String fields. 
• All queries containing aggregate functions 
return a special Apex object called 
AggregateResult, except the no-argument 
form of COUNT, which returns an integer.
Examples 
• Returns Integer or AggregateResult object. 
• Default field names expr0 for the first field, expr1 
for 2nd field, and so on. 
Integer i = [ SELECT COUNT() FROM Timecard__c ]; 
System.debug(i); 
AggregateResult r = [ SELECT 
SUM(Total_Hours__c) Total 
FROM Timecard__c ]; 
System.debug(r.get('Total'));
Grouping Records With Subtotals 
• Two forms of grouping produce subtotals and 
grand totals for the record groupings specified 
in the query. 
• GROUP BY ROLLUP 
• GROUP BY CUBE: causes all possible 
combinations of grouped fields to receive 
subtotals. 
• These replace the GROUP BY syntax and 
support up to 3 grouped fields.
Example of Group By ROLLUP 
for (AggregateResult r : [ SELECT Project__r.Status__c, 
Resource__r.Region__c, 
SUM(Total_Hours__c) hours, COUNT(Id) recs, 
GROUPING(Project__r.Status__c) status, 
GROUPING(Resource__r.Region__c) region 
FROM Timecard__c 
GROUP BY ROLLUP(Project__r.Status__c, Resource__r.Region__c) 
ORDER BY GROUPING(Project__r.Status__c), 
GROUPING(Resource__r.Region__c) ]) 
{ 
System.debug(LoggingLevel.INFO, 
r.get('Status__c') + ' ' + r.get('Region__c') + ' ' + 
r.get('region') + ' ' + r.get('status') + ' ' + 
r.get('hours') + ' ' + r.get('recs')); 
}
Output from example 
16:04:43.207|USER_DEBUG|[7]|INFO|GreenWest 0 0 230.0 6 
16:04:43.207|USER_DEBUG|[7]|INFO|Green Central 0 0 152.0 4 
16:04:43.207|USER_DEBUG|[7]|INFO|Yellow Central 0 0 109.0 3 
16:04:43.207|USER_DEBUG|[7]|INFO|Green null 1 0 382.0 10 
16:04:43.207|USER_DEBUG|[7]|INFO|Yellow null 1 0 109.0 3 
16:04:43.207|USER_DEBUG|[7]|INFO|null null 1 1 491.0 13
SOQL Outer and Inner Joins 
• A SOQL statement consists of a single base object, 
specified using the FROM keyword. 
• All fields in the base object can be retrieved in the 
query, as well as fields from parent and child objects 
depending on their distance away from the base 
object. 
• Force.com takes care of joining related objects 
together to retrieve the requested fields. 
• These implicit joins are always outer joins. An outer 
join returns all records from the base object, including 
records that do not refer to a related object. 
• Adding a where clause makes it an Inner Join.
Examples 
• SOQL Outer Join 
SELECT Name, Account__r.Name 
FROM Proj__c 
• SOQL Inner Join 
SELECT Name, Account__r.Name 
FROM Proj__c 
WHERE Account__c != null
SOQL Semi-Join 
• Allow records from one object to be filtered 
by a subquery against another object. 
• Example of parent-to-child semi-join 
SELECT Id, Name 
FROM Account 
WHERE Id IN 
(SELECT Account__c FROM Proj__c 
WHERE Status__c = 'Yellow')
SOQL with child-to-child Semi-Join 
• Example below selects the records in the 
Timecard object that are filtered by resources 
which have at least one assignment as a 
consultant. 
SELECT Project__r.Name, Week_Ending__c, 
Total_Hours__c 
FROM Timecard__c 
WHERE Resource__c IN 
(SELECT Resource__c FROM Assignment__c 
WHERE Role__c = 'Consultant')
SOQL with child-to-parent Semi-Join 
• Timecards are filtered to include resources with an hourly 
cost rate of more than $100. Child-to-parent refers to the 
relationship between the Timecard and Resource objects. 
• Resource is the parent object, and it is being used to 
restrict the output of the query on Timecard, the child 
object. 
SELECT Project__r.Name, Week_Ending__c, Total_Hours__c 
FROM Timecard__c 
WHERE Resource__c IN 
(SELECT Id FROM Resource__c 
WHERE Hourly_Cost_Rate__c > 100)
SOQL Anti-Join 
• An anti-join is the negative version of a semi-join. 
It uses the NOT IN keyword to allow the subquery 
to exclude records. 
• Example: Query below returns all Accounts 
except those containing Projects in a green 
status. 
SELECT Id, Name 
FROM Account 
WHERE Id NOT IN 
(SELECT Account__c FROM Proj__c 
WHERE Status__c = 'Green')
Restrictions: Semi-Joins and Anti-Joins 
• The selected column in the subquery must be a 
primary or foreign key and cannot traverse 
relationships. It must be a direct field on the child 
object. 
• A single query can include at most two semi-joins or 
anti-joins. 
• SJs and AJs cannot be nested within other SJ and AJ 
statements and are not allowed in subqueries. 
• The parent object cannot be the same type as the 
child. 
• Subqueries cannot be nested and cannot contain the 
OR, count(), ORDER BY, or LIMIT keywords
Semicolon (AND), INCLUDES and 
EXCLUDES for Multi-Select Picklists 
• Query below returns Project records with the 
multiple selection of Apex, Java, and C# in the 
Requested Skills field and also records with 
only Python selected. 
SELECT Id, Name 
FROM Proj__c 
WHERE Requested_Skills__c INCLUDES 
('Apex;Java;C#', 'Python')
SOSL Overview 
• SOSL query specifies search terms and scope. 
• The search terms are a list of string literals and 
can include wildcards. 
• The search scope is fields containing string 
data from one or more objects. This excludes 
Number, Date, and Checkbox fields from being 
searched with SOSL.
SOSL Details 
• Syntax: FIND ’query’ IN search group RETURNING field 
specification LIMIT record limit 
• Apostrophes around query are required. 
• Limited to 20 SOSL queries returning a maximum of 
200 rows per query. 
• Query: one or more words or phrases to search on. 
Can use * or ?. Enclose a search term in quotation 
marks to perform an exact match on multiple words. 
Use the logical operators AND, OR, and AND NOT to 
combine search terms and parentheses to control the 
order in which they’re evaluated. Searches are case-insensitive.
SOSL Details (contd…) 
• Search Group: indicates types of fields to search in each 
object. Valid values are ALL FIELDS (all string fields), NAME 
FIELDS, EMAIL FIELDS, PHONE FIELDS. Default is ALL FIELDS. 
• Field Specification: comma separated list of objects to 
include in the search results. Optionally, you can specify 
additional fields to return by enclosing them in 
parentheses. You can also specify conditional filters using 
the same syntax as the SOQL WHERE clause, set the sort 
order with the ORDER BY keyword, and use the LIMIT 
keyword to limit the number of records returned per 
object. 
• Record Limit: Optional, defaults to 200.
SOSL in Apex 
List<List<SObject>> result = [ 
FIND 'Chicago' 
RETURNING Proj__c(Name), Resource__c(Name) 
]; 
List<Proj__c> projects = (List<Proj__c>)result[0]; 
for (Proj__c project : projects) { 
System.debug('Project: ' + project.Name); 
} 
List<Resource__c> resources = (List<Resource__c>)result[1]; 
for (Resource__c resource : resources) { 
System.debug('Resource: ' + resource.Name); 
}
Transaction Processing 
• Database DML Methods – Add support for 
partial success of a batch. 
• Savepoint - Returning to a savepoint rolls back 
all DML statements executed since the 
creation of the savepoint. 
• Record Locking – provides exclusive write to 
update.
Implicit Transactions in Apex 
• All database operations in Apex are transactional. 
• Every trigger runs in a transaction. If there is an 
uncaught exception in a trigger, all DML 
operations are rolled back. 
• If multiple triggers fire for a single database 
operation, all triggers succeed or fail as a group. 
• DML statements accept a single record or batch 
of records. When operating on a batch, they 
succeed or fail on the entire group of records.
DML Database Methods 
• Allow batch DML operations to fail on 
individual records without impacting the 
entire batch. To do this, they do not throw 
exceptions to indicate error. 
• Instead they return an array of result objects, 
one per input record. These result objects 
contain a flag indicating success or failure, and 
error details in the event of failure.
Database DML Methods 
• A DML database method exists for each of the 
DML statements – insert, update, upsert, delete. 
• Each method takes an optional Boolean 
parameter called opt_allOrNone to specify batch 
behavior. The default value is true, indicating that 
the behavior is “all or none.” 
• This makes the method identical to a DML 
statement, with one failed record causing the 
failure of all records and a DmlException. 
• But if the opt_allOrNone parameter is false, 
partial success is allowed.
Database Savepoint Usage 
void printRecordCount() { 
System.debug([ SELECT COUNT() FROM Resource__c ] + ' records'); 
} 
printRecordCount(); 
Savepoint sp = Database.setSavepoint(); 
delete [ SELECT Id FROM Resource__c ]; 
printRecordCount(); 
Database.rollback(sp); 
printRecordCount();
Record Locking 
• Write locks on records. 
• Use the keyword “for update”. 
• Prevents dirty writes. 
• You cannot use the ORDER BY keyword with FOR 
UPDATE. Query results are automatically ordered 
by Id field. 
Resource__c tim = [ SELECT Id, Hourly_Cost_Rate__c 
FROM Resource__c 
WHERE Name = 'Tim Barr' LIMIT 1 
FOR UPDATE ]; 
tim.Hourly_Cost_Rate__c += 20; 
update tim;
DML Statement Guidelines 
• Max of 200 sObject records in a single method. 
• Operate on only 1 type of sObject at a time. 
• Non-null value for all required fields. 
• Id for current sObject record cannot be modified 
but related IDs can. 
• Upsert can contain 2 separate calls, update & 
insert. 
• Merging works for only 3 records at a time. 
• Merging is Only for Leads, Contacts and Accounts. 
• Commit is implicit, Rollback is explicit.
Database.DMLOptions object 
• Lets you add extra info during a transaction 
like: 
Truncation behavior 
Trigger assignment rules. 
Trigger email notification based on certain events.
Emails – Sending 
• SingleEmailMessage : up to 10 receivers. 
• SingleEmailMessage With Template : unique IDs 
of Contact or Lead objects must be used instead 
of strings to provide the receivers’ email 
addresses. Cannot be used to for internal user 
email addresses. Substitute fields from receiver’s 
record or optional related object. Up to 10 
receivers. Email Templates can be created from 
VF pages. 
• MassEmailMessage : up to 250 receivers.
Messaging.sendEmail Method 
• Transactional - just like DML methods. 
• Can send single email or mass emails. 
• Plain text or Html formats supported. 
• Governor Limits – total 10 invocations per 
context. 
• Single or Mass emails sent from Apex count 
against the daily mass limit. 
MASS_MAIL_LIMIT_EXCEEDED error code if 
limit exceeded.
Limits 
• Max of 1000 emails to external email 
addresses. No limit for internal email 
addresses. 
• Number of external email addresses varies by 
edition (250-Prof, 500-Ent, 1000-unlimited).
Apex Email Services 
• Inbound Email Integration. 
• Classes part of the Messaging namespace. 
• Total messages processed per day = Number 
of user licenses x 1000. 
• Email service addresses from sandbox cannot 
be copied to prod org. 
• Can restrict the domains from which we can 
receive emails.
Inbound Email Objects 
• Write an Apex class that implements a specific interface 
(Messaging.InboundEmailHandler) and method 
(handleInboundEmail). 
• Provides your code access to the 
envelope: InboundEnvelope and 
content: InboundEmail of inbound emails, including body, subject, 
fromAddress, toAddress, binaryAttachments, textAttachments. 
• The return value of this method is an InboundEmailResult object. 
• To indicate processing failure, set the success field of this object to 
false. Any explanatory message set in the message field is returned 
to the sender as an email response.
Inbound Email Processing 
• Create an Email Service using the native user 
interface – service name, apex class, accept 
attachments setting, sending server 
authentication protocols, etc. 
• An Email Service is associated with one or 
more Force.com-issued email addresses that 
serve as the gateways to the Apex class. 
• When email arrives at the email address, your 
Apex class is invoked to process it.
Inbound Email Processing 
• No access to system log in the context of an 
inbound email handler class. Create custom 
objects to log any exceptions or debug 
statements. 
• Request set of incoming emails from the UI 
within a certain date range. Notification sent 
when request is processed. 
• Processing of emails by the email service 
handler can be seen in the Debug logs.
Other Features 
• Apex managed sharing: Rules governing record sharing 
can be controlled in Apex code. 
• Dynamic Apex: Although Apex features strongly typed 
database objects and queries, you can also write code that 
uses database resources dynamically. This carries with it 
the risk of runtime errors but opens up new possibilities of 
dynamic behavior to your applications. The SObject is a 
typeless database object. It allows you to interact with 
database records without declaring them as a specific type. 
• Custom Settings in Apex: You can read and write custom 
settings from Apex like any database object, but without 
the governor limits.
Dynamic Apex 
• Dynamic Apex - no hardcoding of names of fields and objects. 
Schema Describe - similar to metadata API. 
• Dynamic SOQL - no hardcoding of query. 
• Dynamic SOSL 
• Dynamic DML - create sObject dynamically using newSObject 
method on an SObjectType token. Then insert that new object into 
the database. 
Example: 
Account A = new Account(); 
Schema.sObjectType tokenA = A.getSObjectType(); 
Account B = (Account) tokenA.newSObject();
Patterns and Matchers 
• Similar to Java. 
• Reuse requires compilation of the pattern. 
Pattern myPat = Pattern.compile('a*b'); 
Matcher myMatcher = myPat.matcher('aaaab'); 
myMatcher.matches(); 
• Single Invocation: 
Pattern.matches('a*b', 'aaaaab');
System Class 
• abortJob 
• assert, assertEquals, assertNotEquals 
• currentPageReference 
• Debug 
Set the logging level: 
System.debug (Logginglevel.ERROR); 
• getApplicationReadWrite (returns the read write mode set for an 
org during SF.com upgrades and downtimes) 
• isBatch, isFuture, isScheduled 
• now (datetime as GMT), today (date in user’s tz) 
• runAs 
• schedule 
• submit
System.schedule(…) 
• After you implement a class with 
the Schedulable interface, use 
the System.Schedule method to execute it. 
• The scheduler runs as system: all classes are 
executed, whether the user has permission to 
execute the class or not. 
• Example: 
proschedule p = new proschedule(); 
// secs mts HH24 day mon day_of_week optional_yr 
String sch = '0 0 8 13 2 ?'; 
System.schedule('One Time Pro', sch, p);
Library Classes 
• UserInfo - most methods are getter methods like 
getUserId(), getUserName(), 
getOrgId(), getOrgName() 
getDefaultCurrency() 
getLocale() 
getSessionID() 
• Math - abs(), min(...), rand() returns double between 0.0 and 1.0 
• clone() method returns a shallow copy of any SO or CO. 
• Limits class returns the values of governor limits. 
• Two versions for each method. 
Examples: 
Limits.getDMLRows() – amount used in the current context 
Limits.getLimitDMLRows() - amount available in the current context 
• Useful to print using System.debug() for debugging purpose.
Ad

More Related Content

What's hot (19)

SH 2 - SES 3 - MongoDB Aggregation Framework.pptx
SH 2 - SES 3 -  MongoDB Aggregation Framework.pptxSH 2 - SES 3 -  MongoDB Aggregation Framework.pptx
SH 2 - SES 3 - MongoDB Aggregation Framework.pptx
MongoDB
 
The PostgreSQL Query Planner
The PostgreSQL Query PlannerThe PostgreSQL Query Planner
The PostgreSQL Query Planner
Command Prompt., Inc
 
Spark Dataframe - Mr. Jyotiska
Spark Dataframe - Mr. JyotiskaSpark Dataframe - Mr. Jyotiska
Spark Dataframe - Mr. Jyotiska
Sigmoid
 
How to understand and analyze Apache Hive query execution plan for performanc...
How to understand and analyze Apache Hive query execution plan for performanc...How to understand and analyze Apache Hive query execution plan for performanc...
How to understand and analyze Apache Hive query execution plan for performanc...
DataWorks Summit/Hadoop Summit
 
Time Series Meetup: Virtual Edition | July 2020
Time Series Meetup: Virtual Edition | July 2020Time Series Meetup: Virtual Edition | July 2020
Time Series Meetup: Virtual Edition | July 2020
InfluxData
 
Efficient spatial queries on vanilla databases
Efficient spatial queries on vanilla databasesEfficient spatial queries on vanilla databases
Efficient spatial queries on vanilla databases
Julian Hyde
 
ShmooCon 2009 - (Re)Playing(Blind)Sql
ShmooCon 2009 - (Re)Playing(Blind)SqlShmooCon 2009 - (Re)Playing(Blind)Sql
ShmooCon 2009 - (Re)Playing(Blind)Sql
Chema Alonso
 
MySQL 8.0 EXPLAIN ANALYZE
MySQL 8.0 EXPLAIN ANALYZEMySQL 8.0 EXPLAIN ANALYZE
MySQL 8.0 EXPLAIN ANALYZE
Norvald Ryeng
 
Art and Science Come Together When Mastering Relevance Ranking - Tom Burgmans...
Art and Science Come Together When Mastering Relevance Ranking - Tom Burgmans...Art and Science Come Together When Mastering Relevance Ranking - Tom Burgmans...
Art and Science Come Together When Mastering Relevance Ranking - Tom Burgmans...
Lucidworks
 
Apache Calcite Tutorial - BOSS 21
Apache Calcite Tutorial - BOSS 21Apache Calcite Tutorial - BOSS 21
Apache Calcite Tutorial - BOSS 21
Stamatis Zampetakis
 
Data Exploration with Apache Drill: Day 2
Data Exploration with Apache Drill: Day 2Data Exploration with Apache Drill: Day 2
Data Exploration with Apache Drill: Day 2
Charles Givre
 
How to teach an elephant to rock'n'roll
How to teach an elephant to rock'n'rollHow to teach an elephant to rock'n'roll
How to teach an elephant to rock'n'roll
PGConf APAC
 
Time Series Analysis Sample Code
Time Series Analysis Sample CodeTime Series Analysis Sample Code
Time Series Analysis Sample Code
Aiden Wu, FRM
 
ComputeFest 2012: Intro To R for Physical Sciences
ComputeFest 2012: Intro To R for Physical SciencesComputeFest 2012: Intro To R for Physical Sciences
ComputeFest 2012: Intro To R for Physical Sciences
alexstorer
 
Spark Schema For Free with David Szakallas
 Spark Schema For Free with David Szakallas Spark Schema For Free with David Szakallas
Spark Schema For Free with David Szakallas
Databricks
 
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...
Data Con LA
 
Grails GORM - You Know SQL. You Know Queries. Here's GORM.
Grails GORM - You Know SQL. You Know Queries. Here's GORM.Grails GORM - You Know SQL. You Know Queries. Here's GORM.
Grails GORM - You Know SQL. You Know Queries. Here's GORM.
Ted Vinke
 
JavaScript Arrays
JavaScript Arrays JavaScript Arrays
JavaScript Arrays
Reem Alattas
 
Big Data Day LA 2016/ Hadoop/ Spark/ Kafka track - Iterative Spark Developmen...
Big Data Day LA 2016/ Hadoop/ Spark/ Kafka track - Iterative Spark Developmen...Big Data Day LA 2016/ Hadoop/ Spark/ Kafka track - Iterative Spark Developmen...
Big Data Day LA 2016/ Hadoop/ Spark/ Kafka track - Iterative Spark Developmen...
Data Con LA
 
SH 2 - SES 3 - MongoDB Aggregation Framework.pptx
SH 2 - SES 3 -  MongoDB Aggregation Framework.pptxSH 2 - SES 3 -  MongoDB Aggregation Framework.pptx
SH 2 - SES 3 - MongoDB Aggregation Framework.pptx
MongoDB
 
Spark Dataframe - Mr. Jyotiska
Spark Dataframe - Mr. JyotiskaSpark Dataframe - Mr. Jyotiska
Spark Dataframe - Mr. Jyotiska
Sigmoid
 
How to understand and analyze Apache Hive query execution plan for performanc...
How to understand and analyze Apache Hive query execution plan for performanc...How to understand and analyze Apache Hive query execution plan for performanc...
How to understand and analyze Apache Hive query execution plan for performanc...
DataWorks Summit/Hadoop Summit
 
Time Series Meetup: Virtual Edition | July 2020
Time Series Meetup: Virtual Edition | July 2020Time Series Meetup: Virtual Edition | July 2020
Time Series Meetup: Virtual Edition | July 2020
InfluxData
 
Efficient spatial queries on vanilla databases
Efficient spatial queries on vanilla databasesEfficient spatial queries on vanilla databases
Efficient spatial queries on vanilla databases
Julian Hyde
 
ShmooCon 2009 - (Re)Playing(Blind)Sql
ShmooCon 2009 - (Re)Playing(Blind)SqlShmooCon 2009 - (Re)Playing(Blind)Sql
ShmooCon 2009 - (Re)Playing(Blind)Sql
Chema Alonso
 
MySQL 8.0 EXPLAIN ANALYZE
MySQL 8.0 EXPLAIN ANALYZEMySQL 8.0 EXPLAIN ANALYZE
MySQL 8.0 EXPLAIN ANALYZE
Norvald Ryeng
 
Art and Science Come Together When Mastering Relevance Ranking - Tom Burgmans...
Art and Science Come Together When Mastering Relevance Ranking - Tom Burgmans...Art and Science Come Together When Mastering Relevance Ranking - Tom Burgmans...
Art and Science Come Together When Mastering Relevance Ranking - Tom Burgmans...
Lucidworks
 
Apache Calcite Tutorial - BOSS 21
Apache Calcite Tutorial - BOSS 21Apache Calcite Tutorial - BOSS 21
Apache Calcite Tutorial - BOSS 21
Stamatis Zampetakis
 
Data Exploration with Apache Drill: Day 2
Data Exploration with Apache Drill: Day 2Data Exploration with Apache Drill: Day 2
Data Exploration with Apache Drill: Day 2
Charles Givre
 
How to teach an elephant to rock'n'roll
How to teach an elephant to rock'n'rollHow to teach an elephant to rock'n'roll
How to teach an elephant to rock'n'roll
PGConf APAC
 
Time Series Analysis Sample Code
Time Series Analysis Sample CodeTime Series Analysis Sample Code
Time Series Analysis Sample Code
Aiden Wu, FRM
 
ComputeFest 2012: Intro To R for Physical Sciences
ComputeFest 2012: Intro To R for Physical SciencesComputeFest 2012: Intro To R for Physical Sciences
ComputeFest 2012: Intro To R for Physical Sciences
alexstorer
 
Spark Schema For Free with David Szakallas
 Spark Schema For Free with David Szakallas Spark Schema For Free with David Szakallas
Spark Schema For Free with David Szakallas
Databricks
 
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...
Data Con LA
 
Grails GORM - You Know SQL. You Know Queries. Here's GORM.
Grails GORM - You Know SQL. You Know Queries. Here's GORM.Grails GORM - You Know SQL. You Know Queries. Here's GORM.
Grails GORM - You Know SQL. You Know Queries. Here's GORM.
Ted Vinke
 
JavaScript Arrays
JavaScript Arrays JavaScript Arrays
JavaScript Arrays
Reem Alattas
 
Big Data Day LA 2016/ Hadoop/ Spark/ Kafka track - Iterative Spark Developmen...
Big Data Day LA 2016/ Hadoop/ Spark/ Kafka track - Iterative Spark Developmen...Big Data Day LA 2016/ Hadoop/ Spark/ Kafka track - Iterative Spark Developmen...
Big Data Day LA 2016/ Hadoop/ Spark/ Kafka track - Iterative Spark Developmen...
Data Con LA
 

Similar to SFDC Advanced Apex (20)

Sql and PL/SQL Best Practices I
Sql and PL/SQL Best Practices ISql and PL/SQL Best Practices I
Sql and PL/SQL Best Practices I
Carlos Oliveira
 
Advanced SQL For Data Scientists
Advanced SQL For Data ScientistsAdvanced SQL For Data Scientists
Advanced SQL For Data Scientists
Databricks
 
HPD SQL Training - Beginner - 20220916.pptx
HPD SQL Training - Beginner - 20220916.pptxHPD SQL Training - Beginner - 20220916.pptx
HPD SQL Training - Beginner - 20220916.pptx
PatriceRochon1
 
In memory databases presentation
In memory databases presentationIn memory databases presentation
In memory databases presentation
Michael Keane
 
Salesforce Batch processing - Atlanta SFUG
Salesforce Batch processing - Atlanta SFUGSalesforce Batch processing - Atlanta SFUG
Salesforce Batch processing - Atlanta SFUG
vraopolisetti
 
Presentation interpreting execution plans for sql statements
Presentation    interpreting execution plans for sql statementsPresentation    interpreting execution plans for sql statements
Presentation interpreting execution plans for sql statements
xKinAnx
 
Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...
Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...
Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...
Alex Zaballa
 
Advanced tips for making Oracle databases faster
Advanced tips for making Oracle databases fasterAdvanced tips for making Oracle databases faster
Advanced tips for making Oracle databases faster
SolarWinds
 
2013 Collaborate - OAUG - Presentation
2013 Collaborate - OAUG - Presentation2013 Collaborate - OAUG - Presentation
2013 Collaborate - OAUG - Presentation
Biju Thomas
 
IR SQLite Session #1
IR SQLite Session #1IR SQLite Session #1
IR SQLite Session #1
InfoRepos Technologies
 
Optimizer overviewoow2014
Optimizer overviewoow2014Optimizer overviewoow2014
Optimizer overviewoow2014
Mysql User Camp
 
Oracle SQL Tuning
Oracle SQL TuningOracle SQL Tuning
Oracle SQL Tuning
Alex Zaballa
 
Oracle Query Optimizer - An Introduction
Oracle Query Optimizer - An IntroductionOracle Query Optimizer - An Introduction
Oracle Query Optimizer - An Introduction
adryanbub
 
Tutorial - Learn SQL with Live Online Database
Tutorial - Learn SQL with Live Online DatabaseTutorial - Learn SQL with Live Online Database
Tutorial - Learn SQL with Live Online Database
DBrow Adm
 
Query Optimization with MySQL 5.6: Old and New Tricks
Query Optimization with MySQL 5.6: Old and New TricksQuery Optimization with MySQL 5.6: Old and New Tricks
Query Optimization with MySQL 5.6: Old and New Tricks
MYXPLAIN
 
SQL Tunning
SQL TunningSQL Tunning
SQL Tunning
Dhananjay Goel
 
05_DP_300T00A_Optimize.pptx
05_DP_300T00A_Optimize.pptx05_DP_300T00A_Optimize.pptx
05_DP_300T00A_Optimize.pptx
KareemBullard1
 
Query optimizer vivek sharma
Query optimizer vivek sharmaQuery optimizer vivek sharma
Query optimizer vivek sharma
aioughydchapter
 
Introduction to mysql part 3
Introduction to mysql part 3Introduction to mysql part 3
Introduction to mysql part 3
baabtra.com - No. 1 supplier of quality freshers
 
SQL Optimizer vs Hive
SQL Optimizer vs Hive SQL Optimizer vs Hive
SQL Optimizer vs Hive
Vishaka Balasubramanian Sekar
 
Sql and PL/SQL Best Practices I
Sql and PL/SQL Best Practices ISql and PL/SQL Best Practices I
Sql and PL/SQL Best Practices I
Carlos Oliveira
 
Advanced SQL For Data Scientists
Advanced SQL For Data ScientistsAdvanced SQL For Data Scientists
Advanced SQL For Data Scientists
Databricks
 
HPD SQL Training - Beginner - 20220916.pptx
HPD SQL Training - Beginner - 20220916.pptxHPD SQL Training - Beginner - 20220916.pptx
HPD SQL Training - Beginner - 20220916.pptx
PatriceRochon1
 
In memory databases presentation
In memory databases presentationIn memory databases presentation
In memory databases presentation
Michael Keane
 
Salesforce Batch processing - Atlanta SFUG
Salesforce Batch processing - Atlanta SFUGSalesforce Batch processing - Atlanta SFUG
Salesforce Batch processing - Atlanta SFUG
vraopolisetti
 
Presentation interpreting execution plans for sql statements
Presentation    interpreting execution plans for sql statementsPresentation    interpreting execution plans for sql statements
Presentation interpreting execution plans for sql statements
xKinAnx
 
Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...
Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...
Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...
Alex Zaballa
 
Advanced tips for making Oracle databases faster
Advanced tips for making Oracle databases fasterAdvanced tips for making Oracle databases faster
Advanced tips for making Oracle databases faster
SolarWinds
 
2013 Collaborate - OAUG - Presentation
2013 Collaborate - OAUG - Presentation2013 Collaborate - OAUG - Presentation
2013 Collaborate - OAUG - Presentation
Biju Thomas
 
Optimizer overviewoow2014
Optimizer overviewoow2014Optimizer overviewoow2014
Optimizer overviewoow2014
Mysql User Camp
 
Oracle Query Optimizer - An Introduction
Oracle Query Optimizer - An IntroductionOracle Query Optimizer - An Introduction
Oracle Query Optimizer - An Introduction
adryanbub
 
Tutorial - Learn SQL with Live Online Database
Tutorial - Learn SQL with Live Online DatabaseTutorial - Learn SQL with Live Online Database
Tutorial - Learn SQL with Live Online Database
DBrow Adm
 
Query Optimization with MySQL 5.6: Old and New Tricks
Query Optimization with MySQL 5.6: Old and New TricksQuery Optimization with MySQL 5.6: Old and New Tricks
Query Optimization with MySQL 5.6: Old and New Tricks
MYXPLAIN
 
05_DP_300T00A_Optimize.pptx
05_DP_300T00A_Optimize.pptx05_DP_300T00A_Optimize.pptx
05_DP_300T00A_Optimize.pptx
KareemBullard1
 
Query optimizer vivek sharma
Query optimizer vivek sharmaQuery optimizer vivek sharma
Query optimizer vivek sharma
aioughydchapter
 
Ad

More from Sujit Kumar (20)

Introduction to OOP with java
Introduction to OOP with javaIntroduction to OOP with java
Introduction to OOP with java
Sujit Kumar
 
SFDC Database Basics
SFDC Database BasicsSFDC Database Basics
SFDC Database Basics
Sujit Kumar
 
SFDC Database Security
SFDC Database SecuritySFDC Database Security
SFDC Database Security
Sujit Kumar
 
SFDC Social Applications
SFDC Social ApplicationsSFDC Social Applications
SFDC Social Applications
Sujit Kumar
 
SFDC Other Platform Features
SFDC Other Platform FeaturesSFDC Other Platform Features
SFDC Other Platform Features
Sujit Kumar
 
SFDC Outbound Integrations
SFDC Outbound IntegrationsSFDC Outbound Integrations
SFDC Outbound Integrations
Sujit Kumar
 
SFDC Inbound Integrations
SFDC Inbound IntegrationsSFDC Inbound Integrations
SFDC Inbound Integrations
Sujit Kumar
 
SFDC UI - Advanced Visualforce
SFDC UI - Advanced VisualforceSFDC UI - Advanced Visualforce
SFDC UI - Advanced Visualforce
Sujit Kumar
 
SFDC UI - Introduction to Visualforce
SFDC UI -  Introduction to VisualforceSFDC UI -  Introduction to Visualforce
SFDC UI - Introduction to Visualforce
Sujit Kumar
 
SFDC Deployments
SFDC DeploymentsSFDC Deployments
SFDC Deployments
Sujit Kumar
 
SFDC Batch Apex
SFDC Batch ApexSFDC Batch Apex
SFDC Batch Apex
Sujit Kumar
 
SFDC Data Loader
SFDC Data LoaderSFDC Data Loader
SFDC Data Loader
Sujit Kumar
 
SFDC Introduction to Apex
SFDC Introduction to ApexSFDC Introduction to Apex
SFDC Introduction to Apex
Sujit Kumar
 
SFDC Database Additional Features
SFDC Database Additional FeaturesSFDC Database Additional Features
SFDC Database Additional Features
Sujit Kumar
 
Introduction to SalesForce
Introduction to SalesForceIntroduction to SalesForce
Introduction to SalesForce
Sujit Kumar
 
More about java strings - Immutability and String Pool
More about java strings - Immutability and String PoolMore about java strings - Immutability and String Pool
More about java strings - Immutability and String Pool
Sujit Kumar
 
Hibernate First and Second level caches
Hibernate First and Second level cachesHibernate First and Second level caches
Hibernate First and Second level caches
Sujit Kumar
 
Java equals hashCode Contract
Java equals hashCode ContractJava equals hashCode Contract
Java equals hashCode Contract
Sujit Kumar
 
Java Comparable and Comparator
Java Comparable and ComparatorJava Comparable and Comparator
Java Comparable and Comparator
Sujit Kumar
 
Java build tools
Java build toolsJava build tools
Java build tools
Sujit Kumar
 
Introduction to OOP with java
Introduction to OOP with javaIntroduction to OOP with java
Introduction to OOP with java
Sujit Kumar
 
SFDC Database Basics
SFDC Database BasicsSFDC Database Basics
SFDC Database Basics
Sujit Kumar
 
SFDC Database Security
SFDC Database SecuritySFDC Database Security
SFDC Database Security
Sujit Kumar
 
SFDC Social Applications
SFDC Social ApplicationsSFDC Social Applications
SFDC Social Applications
Sujit Kumar
 
SFDC Other Platform Features
SFDC Other Platform FeaturesSFDC Other Platform Features
SFDC Other Platform Features
Sujit Kumar
 
SFDC Outbound Integrations
SFDC Outbound IntegrationsSFDC Outbound Integrations
SFDC Outbound Integrations
Sujit Kumar
 
SFDC Inbound Integrations
SFDC Inbound IntegrationsSFDC Inbound Integrations
SFDC Inbound Integrations
Sujit Kumar
 
SFDC UI - Advanced Visualforce
SFDC UI - Advanced VisualforceSFDC UI - Advanced Visualforce
SFDC UI - Advanced Visualforce
Sujit Kumar
 
SFDC UI - Introduction to Visualforce
SFDC UI -  Introduction to VisualforceSFDC UI -  Introduction to Visualforce
SFDC UI - Introduction to Visualforce
Sujit Kumar
 
SFDC Deployments
SFDC DeploymentsSFDC Deployments
SFDC Deployments
Sujit Kumar
 
SFDC Data Loader
SFDC Data LoaderSFDC Data Loader
SFDC Data Loader
Sujit Kumar
 
SFDC Introduction to Apex
SFDC Introduction to ApexSFDC Introduction to Apex
SFDC Introduction to Apex
Sujit Kumar
 
SFDC Database Additional Features
SFDC Database Additional FeaturesSFDC Database Additional Features
SFDC Database Additional Features
Sujit Kumar
 
Introduction to SalesForce
Introduction to SalesForceIntroduction to SalesForce
Introduction to SalesForce
Sujit Kumar
 
More about java strings - Immutability and String Pool
More about java strings - Immutability and String PoolMore about java strings - Immutability and String Pool
More about java strings - Immutability and String Pool
Sujit Kumar
 
Hibernate First and Second level caches
Hibernate First and Second level cachesHibernate First and Second level caches
Hibernate First and Second level caches
Sujit Kumar
 
Java equals hashCode Contract
Java equals hashCode ContractJava equals hashCode Contract
Java equals hashCode Contract
Sujit Kumar
 
Java Comparable and Comparator
Java Comparable and ComparatorJava Comparable and Comparator
Java Comparable and Comparator
Sujit Kumar
 
Java build tools
Java build toolsJava build tools
Java build tools
Sujit Kumar
 
Ad

Recently uploaded (20)

Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Raffi Khatchadourian
 
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Wonjun Hwang
 
Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?
Eric Torreborre
 
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz
 
Viam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdfViam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdf
camilalamoratta
 
Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)
Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)
Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)
CSUC - Consorci de Serveis Universitaris de Catalunya
 
Unlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web AppsUnlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web Apps
Maximiliano Firtman
 
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Safe Software
 
AI You Can Trust: The Critical Role of Governance and Quality.pdf
AI You Can Trust: The Critical Role of Governance and Quality.pdfAI You Can Trust: The Critical Role of Governance and Quality.pdf
AI You Can Trust: The Critical Role of Governance and Quality.pdf
Precisely
 
Jignesh Shah - The Innovator and Czar of Exchanges
Jignesh Shah - The Innovator and Czar of ExchangesJignesh Shah - The Innovator and Czar of Exchanges
Jignesh Shah - The Innovator and Czar of Exchanges
Jignesh Shah Innovator
 
Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptxSmart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Seasia Infotech
 
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
Ivano Malavolta
 
Q1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor PresentationQ1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor Presentation
Dropbox
 
IT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information TechnologyIT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information Technology
SHEHABALYAMANI
 
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdfKit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Wonjun Hwang
 
Bepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firmBepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firm
Benard76
 
Cybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and MitigationCybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and Mitigation
VICTOR MAESTRE RAMIREZ
 
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Mike Mingos
 
UiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer OpportunitiesUiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer Opportunities
DianaGray10
 
Agentic Automation - Delhi UiPath Community Meetup
Agentic Automation - Delhi UiPath Community MeetupAgentic Automation - Delhi UiPath Community Meetup
Agentic Automation - Delhi UiPath Community Meetup
Manoj Batra (1600 + Connections)
 
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Raffi Khatchadourian
 
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Wonjun Hwang
 
Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?
Eric Torreborre
 
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz
 
Viam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdfViam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdf
camilalamoratta
 
Unlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web AppsUnlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web Apps
Maximiliano Firtman
 
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Safe Software
 
AI You Can Trust: The Critical Role of Governance and Quality.pdf
AI You Can Trust: The Critical Role of Governance and Quality.pdfAI You Can Trust: The Critical Role of Governance and Quality.pdf
AI You Can Trust: The Critical Role of Governance and Quality.pdf
Precisely
 
Jignesh Shah - The Innovator and Czar of Exchanges
Jignesh Shah - The Innovator and Czar of ExchangesJignesh Shah - The Innovator and Czar of Exchanges
Jignesh Shah - The Innovator and Czar of Exchanges
Jignesh Shah Innovator
 
Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptxSmart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Seasia Infotech
 
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
Ivano Malavolta
 
Q1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor PresentationQ1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor Presentation
Dropbox
 
IT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information TechnologyIT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information Technology
SHEHABALYAMANI
 
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdfKit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Wonjun Hwang
 
Bepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firmBepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firm
Benard76
 
Cybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and MitigationCybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and Mitigation
VICTOR MAESTRE RAMIREZ
 
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Mike Mingos
 
UiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer OpportunitiesUiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer Opportunities
DianaGray10
 

SFDC Advanced Apex

  • 1. Force.com Apex Advanced Sujit Kumar Zenolocity LLC © 2012 - 2024
  • 2. Overview • Aggregate SOQL Features • Additional SOQL Features • SOSL • Transaction Processing • Managed Sharing • Send & Receive Email • Dynamic Apex • Patterns and Matchers • Custom Settings in Apex • System class and methods
  • 3. Aggregate Functions • AVG, COUNT, COUNT_DISTINCT, MIN, MAX, SUM. • AVG, SUM : Operate on Numeric Fields only. • COUNT, COUNT_DISTINCT, MIN, MAX: Numeric, Date, String fields. • All queries containing aggregate functions return a special Apex object called AggregateResult, except the no-argument form of COUNT, which returns an integer.
  • 4. Examples • Returns Integer or AggregateResult object. • Default field names expr0 for the first field, expr1 for 2nd field, and so on. Integer i = [ SELECT COUNT() FROM Timecard__c ]; System.debug(i); AggregateResult r = [ SELECT SUM(Total_Hours__c) Total FROM Timecard__c ]; System.debug(r.get('Total'));
  • 5. Grouping Records With Subtotals • Two forms of grouping produce subtotals and grand totals for the record groupings specified in the query. • GROUP BY ROLLUP • GROUP BY CUBE: causes all possible combinations of grouped fields to receive subtotals. • These replace the GROUP BY syntax and support up to 3 grouped fields.
  • 6. Example of Group By ROLLUP for (AggregateResult r : [ SELECT Project__r.Status__c, Resource__r.Region__c, SUM(Total_Hours__c) hours, COUNT(Id) recs, GROUPING(Project__r.Status__c) status, GROUPING(Resource__r.Region__c) region FROM Timecard__c GROUP BY ROLLUP(Project__r.Status__c, Resource__r.Region__c) ORDER BY GROUPING(Project__r.Status__c), GROUPING(Resource__r.Region__c) ]) { System.debug(LoggingLevel.INFO, r.get('Status__c') + ' ' + r.get('Region__c') + ' ' + r.get('region') + ' ' + r.get('status') + ' ' + r.get('hours') + ' ' + r.get('recs')); }
  • 7. Output from example 16:04:43.207|USER_DEBUG|[7]|INFO|GreenWest 0 0 230.0 6 16:04:43.207|USER_DEBUG|[7]|INFO|Green Central 0 0 152.0 4 16:04:43.207|USER_DEBUG|[7]|INFO|Yellow Central 0 0 109.0 3 16:04:43.207|USER_DEBUG|[7]|INFO|Green null 1 0 382.0 10 16:04:43.207|USER_DEBUG|[7]|INFO|Yellow null 1 0 109.0 3 16:04:43.207|USER_DEBUG|[7]|INFO|null null 1 1 491.0 13
  • 8. SOQL Outer and Inner Joins • A SOQL statement consists of a single base object, specified using the FROM keyword. • All fields in the base object can be retrieved in the query, as well as fields from parent and child objects depending on their distance away from the base object. • Force.com takes care of joining related objects together to retrieve the requested fields. • These implicit joins are always outer joins. An outer join returns all records from the base object, including records that do not refer to a related object. • Adding a where clause makes it an Inner Join.
  • 9. Examples • SOQL Outer Join SELECT Name, Account__r.Name FROM Proj__c • SOQL Inner Join SELECT Name, Account__r.Name FROM Proj__c WHERE Account__c != null
  • 10. SOQL Semi-Join • Allow records from one object to be filtered by a subquery against another object. • Example of parent-to-child semi-join SELECT Id, Name FROM Account WHERE Id IN (SELECT Account__c FROM Proj__c WHERE Status__c = 'Yellow')
  • 11. SOQL with child-to-child Semi-Join • Example below selects the records in the Timecard object that are filtered by resources which have at least one assignment as a consultant. SELECT Project__r.Name, Week_Ending__c, Total_Hours__c FROM Timecard__c WHERE Resource__c IN (SELECT Resource__c FROM Assignment__c WHERE Role__c = 'Consultant')
  • 12. SOQL with child-to-parent Semi-Join • Timecards are filtered to include resources with an hourly cost rate of more than $100. Child-to-parent refers to the relationship between the Timecard and Resource objects. • Resource is the parent object, and it is being used to restrict the output of the query on Timecard, the child object. SELECT Project__r.Name, Week_Ending__c, Total_Hours__c FROM Timecard__c WHERE Resource__c IN (SELECT Id FROM Resource__c WHERE Hourly_Cost_Rate__c > 100)
  • 13. SOQL Anti-Join • An anti-join is the negative version of a semi-join. It uses the NOT IN keyword to allow the subquery to exclude records. • Example: Query below returns all Accounts except those containing Projects in a green status. SELECT Id, Name FROM Account WHERE Id NOT IN (SELECT Account__c FROM Proj__c WHERE Status__c = 'Green')
  • 14. Restrictions: Semi-Joins and Anti-Joins • The selected column in the subquery must be a primary or foreign key and cannot traverse relationships. It must be a direct field on the child object. • A single query can include at most two semi-joins or anti-joins. • SJs and AJs cannot be nested within other SJ and AJ statements and are not allowed in subqueries. • The parent object cannot be the same type as the child. • Subqueries cannot be nested and cannot contain the OR, count(), ORDER BY, or LIMIT keywords
  • 15. Semicolon (AND), INCLUDES and EXCLUDES for Multi-Select Picklists • Query below returns Project records with the multiple selection of Apex, Java, and C# in the Requested Skills field and also records with only Python selected. SELECT Id, Name FROM Proj__c WHERE Requested_Skills__c INCLUDES ('Apex;Java;C#', 'Python')
  • 16. SOSL Overview • SOSL query specifies search terms and scope. • The search terms are a list of string literals and can include wildcards. • The search scope is fields containing string data from one or more objects. This excludes Number, Date, and Checkbox fields from being searched with SOSL.
  • 17. SOSL Details • Syntax: FIND ’query’ IN search group RETURNING field specification LIMIT record limit • Apostrophes around query are required. • Limited to 20 SOSL queries returning a maximum of 200 rows per query. • Query: one or more words or phrases to search on. Can use * or ?. Enclose a search term in quotation marks to perform an exact match on multiple words. Use the logical operators AND, OR, and AND NOT to combine search terms and parentheses to control the order in which they’re evaluated. Searches are case-insensitive.
  • 18. SOSL Details (contd…) • Search Group: indicates types of fields to search in each object. Valid values are ALL FIELDS (all string fields), NAME FIELDS, EMAIL FIELDS, PHONE FIELDS. Default is ALL FIELDS. • Field Specification: comma separated list of objects to include in the search results. Optionally, you can specify additional fields to return by enclosing them in parentheses. You can also specify conditional filters using the same syntax as the SOQL WHERE clause, set the sort order with the ORDER BY keyword, and use the LIMIT keyword to limit the number of records returned per object. • Record Limit: Optional, defaults to 200.
  • 19. SOSL in Apex List<List<SObject>> result = [ FIND 'Chicago' RETURNING Proj__c(Name), Resource__c(Name) ]; List<Proj__c> projects = (List<Proj__c>)result[0]; for (Proj__c project : projects) { System.debug('Project: ' + project.Name); } List<Resource__c> resources = (List<Resource__c>)result[1]; for (Resource__c resource : resources) { System.debug('Resource: ' + resource.Name); }
  • 20. Transaction Processing • Database DML Methods – Add support for partial success of a batch. • Savepoint - Returning to a savepoint rolls back all DML statements executed since the creation of the savepoint. • Record Locking – provides exclusive write to update.
  • 21. Implicit Transactions in Apex • All database operations in Apex are transactional. • Every trigger runs in a transaction. If there is an uncaught exception in a trigger, all DML operations are rolled back. • If multiple triggers fire for a single database operation, all triggers succeed or fail as a group. • DML statements accept a single record or batch of records. When operating on a batch, they succeed or fail on the entire group of records.
  • 22. DML Database Methods • Allow batch DML operations to fail on individual records without impacting the entire batch. To do this, they do not throw exceptions to indicate error. • Instead they return an array of result objects, one per input record. These result objects contain a flag indicating success or failure, and error details in the event of failure.
  • 23. Database DML Methods • A DML database method exists for each of the DML statements – insert, update, upsert, delete. • Each method takes an optional Boolean parameter called opt_allOrNone to specify batch behavior. The default value is true, indicating that the behavior is “all or none.” • This makes the method identical to a DML statement, with one failed record causing the failure of all records and a DmlException. • But if the opt_allOrNone parameter is false, partial success is allowed.
  • 24. Database Savepoint Usage void printRecordCount() { System.debug([ SELECT COUNT() FROM Resource__c ] + ' records'); } printRecordCount(); Savepoint sp = Database.setSavepoint(); delete [ SELECT Id FROM Resource__c ]; printRecordCount(); Database.rollback(sp); printRecordCount();
  • 25. Record Locking • Write locks on records. • Use the keyword “for update”. • Prevents dirty writes. • You cannot use the ORDER BY keyword with FOR UPDATE. Query results are automatically ordered by Id field. Resource__c tim = [ SELECT Id, Hourly_Cost_Rate__c FROM Resource__c WHERE Name = 'Tim Barr' LIMIT 1 FOR UPDATE ]; tim.Hourly_Cost_Rate__c += 20; update tim;
  • 26. DML Statement Guidelines • Max of 200 sObject records in a single method. • Operate on only 1 type of sObject at a time. • Non-null value for all required fields. • Id for current sObject record cannot be modified but related IDs can. • Upsert can contain 2 separate calls, update & insert. • Merging works for only 3 records at a time. • Merging is Only for Leads, Contacts and Accounts. • Commit is implicit, Rollback is explicit.
  • 27. Database.DMLOptions object • Lets you add extra info during a transaction like: Truncation behavior Trigger assignment rules. Trigger email notification based on certain events.
  • 28. Emails – Sending • SingleEmailMessage : up to 10 receivers. • SingleEmailMessage With Template : unique IDs of Contact or Lead objects must be used instead of strings to provide the receivers’ email addresses. Cannot be used to for internal user email addresses. Substitute fields from receiver’s record or optional related object. Up to 10 receivers. Email Templates can be created from VF pages. • MassEmailMessage : up to 250 receivers.
  • 29. Messaging.sendEmail Method • Transactional - just like DML methods. • Can send single email or mass emails. • Plain text or Html formats supported. • Governor Limits – total 10 invocations per context. • Single or Mass emails sent from Apex count against the daily mass limit. MASS_MAIL_LIMIT_EXCEEDED error code if limit exceeded.
  • 30. Limits • Max of 1000 emails to external email addresses. No limit for internal email addresses. • Number of external email addresses varies by edition (250-Prof, 500-Ent, 1000-unlimited).
  • 31. Apex Email Services • Inbound Email Integration. • Classes part of the Messaging namespace. • Total messages processed per day = Number of user licenses x 1000. • Email service addresses from sandbox cannot be copied to prod org. • Can restrict the domains from which we can receive emails.
  • 32. Inbound Email Objects • Write an Apex class that implements a specific interface (Messaging.InboundEmailHandler) and method (handleInboundEmail). • Provides your code access to the envelope: InboundEnvelope and content: InboundEmail of inbound emails, including body, subject, fromAddress, toAddress, binaryAttachments, textAttachments. • The return value of this method is an InboundEmailResult object. • To indicate processing failure, set the success field of this object to false. Any explanatory message set in the message field is returned to the sender as an email response.
  • 33. Inbound Email Processing • Create an Email Service using the native user interface – service name, apex class, accept attachments setting, sending server authentication protocols, etc. • An Email Service is associated with one or more Force.com-issued email addresses that serve as the gateways to the Apex class. • When email arrives at the email address, your Apex class is invoked to process it.
  • 34. Inbound Email Processing • No access to system log in the context of an inbound email handler class. Create custom objects to log any exceptions or debug statements. • Request set of incoming emails from the UI within a certain date range. Notification sent when request is processed. • Processing of emails by the email service handler can be seen in the Debug logs.
  • 35. Other Features • Apex managed sharing: Rules governing record sharing can be controlled in Apex code. • Dynamic Apex: Although Apex features strongly typed database objects and queries, you can also write code that uses database resources dynamically. This carries with it the risk of runtime errors but opens up new possibilities of dynamic behavior to your applications. The SObject is a typeless database object. It allows you to interact with database records without declaring them as a specific type. • Custom Settings in Apex: You can read and write custom settings from Apex like any database object, but without the governor limits.
  • 36. Dynamic Apex • Dynamic Apex - no hardcoding of names of fields and objects. Schema Describe - similar to metadata API. • Dynamic SOQL - no hardcoding of query. • Dynamic SOSL • Dynamic DML - create sObject dynamically using newSObject method on an SObjectType token. Then insert that new object into the database. Example: Account A = new Account(); Schema.sObjectType tokenA = A.getSObjectType(); Account B = (Account) tokenA.newSObject();
  • 37. Patterns and Matchers • Similar to Java. • Reuse requires compilation of the pattern. Pattern myPat = Pattern.compile('a*b'); Matcher myMatcher = myPat.matcher('aaaab'); myMatcher.matches(); • Single Invocation: Pattern.matches('a*b', 'aaaaab');
  • 38. System Class • abortJob • assert, assertEquals, assertNotEquals • currentPageReference • Debug Set the logging level: System.debug (Logginglevel.ERROR); • getApplicationReadWrite (returns the read write mode set for an org during SF.com upgrades and downtimes) • isBatch, isFuture, isScheduled • now (datetime as GMT), today (date in user’s tz) • runAs • schedule • submit
  • 39. System.schedule(…) • After you implement a class with the Schedulable interface, use the System.Schedule method to execute it. • The scheduler runs as system: all classes are executed, whether the user has permission to execute the class or not. • Example: proschedule p = new proschedule(); // secs mts HH24 day mon day_of_week optional_yr String sch = '0 0 8 13 2 ?'; System.schedule('One Time Pro', sch, p);
  • 40. Library Classes • UserInfo - most methods are getter methods like getUserId(), getUserName(), getOrgId(), getOrgName() getDefaultCurrency() getLocale() getSessionID() • Math - abs(), min(...), rand() returns double between 0.0 and 1.0 • clone() method returns a shallow copy of any SO or CO. • Limits class returns the values of governor limits. • Two versions for each method. Examples: Limits.getDMLRows() – amount used in the current context Limits.getLimitDMLRows() - amount available in the current context • Useful to print using System.debug() for debugging purpose.
  翻译: