"Jahan clicks ruk jaate hain, wahan code shuru hota hai."
"Where clicks stop, code begins." Apex is how you build what configuration can't.
- When do I need code?
- What is a transaction?
- Why 100 queries?
- All or nothing?
- Whose permissions?
Step 5, Part A: Apex and Transactions
Our method's Step 5 builds transactions that touch several sObjects at once. You will learn Apex, Salesforce's programming language: classes, collections, SOQL, DML, exceptions, governor limits and security, then build an all-or-nothing booking transaction for Kaveri Motors and a claim settlement for Suraksha.
You are hereSteps 1-4 Requirements and configurationSteps 5-9 DevelopmentSteps 10-11 Test and deploySteps 12-15 Rollout
Hook: the half-saved booking
At Kaveri Motors, confirming a booking means five changes at once: create the order, add the car to it, activate it, move the deal to Booked, and give the delivery team a task.
One Saturday, the network dropped after step two. The order existed, with the car on it, but the deal still said Negotiation and nobody told the delivery team. The customer came to collect her car three weeks later and nobody had prepared it.
A flow can do several steps, but this needs checks, calculations and a guarantee: all five changes happen, or none do. That guarantee is a transaction, and Apex lets you control it precisely.
By the end of this workbook, you will be able to
- Decide when a requirement needs Apex instead of clicks.
- Set up VS Code, the Salesforce CLI and your org, and run Apex.
- Write Apex with variables, collections, classes, methods and exceptions.
- Query with SOQL and change data with DML, including partial success.
- Explain transactions and governor limits, and write bulk-safe code.
- Respect sharing and permissions with
with sharingand user mode. - Build a multi-object, all-or-nothing transaction with savepoints.
Concept: when code, and its limits
Clicks before code
Use the simplest tool that works, as in every step so far. Choose Apex only when one of these is true:
What is a transaction?
A transaction is everything that happens from one request to its final save: a button click, a data load, a flow, a trigger. If any part fails, Salesforce undoes all of it, unless you handle the failure yourself.
Governor limits: sharing one building
Salesforce is multi-tenant: thousands of companies share the same servers, like flats sharing one housing society's water tank. So that no flat drains the tank, every transaction gets a fixed allowance. Exceed it, and Salesforce stops the transaction and rolls it back.
You can see where you stand at any moment with the Limits class, for example Limits.getQueries() and Limits.getLimitQueries().
Set up your developer tools
- Install Visual Studio Code, then the Salesforce Extension Pack from its Extensions panel.
- Install the Salesforce CLI from Salesforce's developer site. In a terminal, check it with
sf --version. - In VS Code, open the command palette and run SFDX: Create Project. Name it kaveri-dev.
- Run SFDX: Authorize an Org, choose Production, log in to Org C, and give it the alias orgC. Do the same for Org D as orgD in a second project, suraksha-dev.
- Run SFDX: Create Apex Class and name it HelloKaveri. Write a method, then right-click and choose SFDX: Deploy This Source to Org.
- Create a file scripts/apex/hello.apex, write
System.debug(HelloKaveri.greet('Priya'));, select it and run SFDX: Execute Anonymous Apex with Currently Selected Text. Read the debug output.
Useful CLI commands
The Apex language
Apex looks like Java. It is strongly typed: every variable has a type, and the compiler checks your code before it runs.
Variables and types
Collections: List, Set and Map
Classes, methods and exceptions
Calling Apex from other places
SOQL and DML
SOQL: reading data
SOSL searches text across several objects at once, like the global search box: FIND 'Priya' IN ALL FIELDS RETURNING Account(Name), Lead(Name). Use SOQL when you know the object; SOSL when you're searching.
DML: changing data
All or nothing, or partial success?
Sharing and security in Apex
By default, Apex runs in system mode: it ignores the running user's object permissions and field-level security from Step 12. You must choose to respect them.
with sharing on every class, query WITH USER_MODE, and use insert as user and similar for DML, unless there's a written reason not to.Writing bulk-safe code
Your code will rarely handle one record. A data load, a flow or a trigger can pass it 200 at once. Code written for one record breaks at scale.
Breaks at scale
Bulk-safe
Try it: watch the limits
The bulk-safe checklist
Demo: Kaveri booking transaction
The transaction from the hook, built properly. This class is used again by the booking component in Part B.
What the transaction does
Walk through the code
Run it
- Deploy BookingService to Org C.
- Find an opportunity with a car on it, in Negotiation. Copy its ID from the URL.
- In Execute Anonymous, run
System.debug(BookingService.book('PASTE_ID', 21000, 'RCPT-1001', 'Pearl White')); - Check the new Order, its product, the deal at Booked, and the task.
- Now run it with a booking amount of 5000. Read the error and confirm nothing was created.
- Finally, temporarily make the Task's Subject field required by a validation rule that always fails, run a valid booking, and confirm the order was rolled back too. Then delete the rule.
Practice: Suraksha claim settlement
Write the settlement transaction for Suraksha in Org D, from these requirements. Try it before opening the model answer.
Open the model answer after you've written your own
Compare your version: did you check access, guard against nulls, use a savepoint, and give the user a clear message?
Three exercises
Exercise 1: Collections and SOQL in Execute Anonymous
- In Org C, write a script that builds a
Map<String, Integer>of open deals per stage using one SOQL query and a loop, and prints it. - Rewrite it with an aggregate query,
GROUP BY StageName. Which is better, and why? - Find every customer who owns more than one car, using an aggregate query on Asset grouped by AccountId with
HAVING COUNT(Id) > 1. - Print
Limits.getQueries()at the end of each script.
Exercise 2: Prove the booking transaction is all-or-nothing
Run the Demo's six "Run it" steps, and record each result in your Code Pack. Then answer: what would happen without the savepoint, if the task insert failed?
Exercise 3: Find the problem
Each snippet compiles, but will cause trouble. Choose the main problem.
Build your Code Pack
Record each class and method, what it does, the limits it uses, and how you tested it. Your work saves in this browser on this device.
Build with AI
AI coding tools, such as Agentforce Vibes in your Developer Edition org or Claude Code connected through the Salesforce DX MCP Server, can write Apex quickly. A developer who can't read and judge that code can't be trusted with it.
Reflect and exit check
Quick test
Exit check: are you ready for Part B?
@AuraEnabled method. In Part B, a Lightning Web Component calls it from a button on the opportunity page.Interview preparation
Apex questions are the core of developer interviews. Practise these aloud, then use our AI interview agents for feedback.
For your resume and portfolio
Trainer notes
Open the suggested session plan and coaching notes
| Session | Cover | Students leave with |
|---|---|---|
| 1 (90 min) | Hook, when code, transactions and limits. Set up VS Code and the CLI together. | HelloKaveri deployed and run |
| 2 (90 min) | The language: types, collections, classes, exceptions. Live coding the calculator. | Calculator working |
| 3 (90 min) | SOQL, DML, partial success, security. Exercise 1. | Exercise 1 done |
| 4 (90 min) | Bulk-safe code and the limits simulator. BookingService live, line by line. | Exercise 2 done |
| 5 (90 min) | Suraksha practice, Exercise 3, code reviews in pairs. | Code Pack, reflection and exit check |
Common mistakes to catch
- Queries or DML inside loops. Run the 200-record test every time.
- Using Double for money. Use Decimal.
- Single-record query assignment,
Account a = [SELECT ...], which throws when nothing is found. Query into a list and check it. - Catching exceptions and doing nothing, so failures vanish silently.
- Leaving out the sharing keyword, or querying without user mode.
- Hard-coded IDs, which differ between orgs.
Check before each batch
Install the current CLI and extensions on a clean machine and walk through setup; menu names change. Note that tests are taught fully in Step 10, but students should already run their code in Execute Anonymous.