SalesforceWizard

Salesforce Apex tutorial for beginners

On this page (10 sections)Lesson 1: Apex basicsLesson 2: Working with data: SOQL and DMLLesson 3: TriggersLesson 4: Asynchronous ApexLesson 5: Testing and deploymentLesson 6: Classes and object-oriented ApexWhat changed in 2025–26How this is asked in interviewsPractise this topicCommon questions

Apex is Salesforce's programming language. It looks like Java and runs on Salesforce's servers, with limits that keep the shared platform fast. Use it when Flow is not enough: complex logic, large data volumes and integrations.

In this topic: Lesson 1: Apex basics · Lesson 2: Working with data: SOQL and DML · Lesson 3: Triggers · Lesson 4: Asynchronous Apex · Lesson 5: Testing and deployment · Lesson 6: Classes and object-oriented Apex

Lesson 1: Apex basics

public with sharing class AccountService {
    public static void markVip(List<Account> accounts) {
        for (Account a : accounts) {
            if (a.AnnualRevenue != null && a.AnnualRevenue > 10000000) {
                a.Rating = 'Hot';
            }
        }
    }
}
  • Data types include Integer, Decimal, String, Boolean, Date, Id and sObjects such as Account.
  • Collections: List (ordered), Set (unique values) and Map (key to value). Maps are the most useful for bulk code.
  • with sharing makes the class respect the user's record access. Use it by default.
  • Write code in VS Code with the Salesforce Extensions, or the Developer Console for quick checks.

Lesson 2: Working with data: SOQL and DML

List<Contact> contacts = [SELECT Id, Email FROM Contact WHERE AccountId = :accId WITH USER_MODE];
for (Contact c : contacts) c.Email_Verified__c = true;
update contacts;

DML statements (insert, update, upsert, delete) save data. Database.insert(records, false) allows partial success and returns results you can check for errors.

Tip: Governor limits are per transaction: 100 SOQL queries and 150 DML statements (synchronous). Write every piece of code to handle 200 records at once, not one.

Lesson 3: Triggers

A trigger runs Apex before or after records are inserted, updated, deleted or undeleted. Keep one trigger per object and move the logic into a handler class.

trigger OpportunityTrigger on Opportunity (before update, after update) {
    if (Trigger.isBefore) OpportunityHandler.beforeUpdate(Trigger.new, Trigger.oldMap);
    if (Trigger.isAfter)  OpportunityHandler.afterUpdate(Trigger.new, Trigger.oldMap);
}
  • Use before triggers to change fields on the same records (no DML needed).
  • Use after triggers to work with other records or when you need the record Id.
  • Compare Trigger.oldMap with Trigger.new so logic runs only when a field actually changed.
  • Prevent recursion with a static flag or a static Set of processed Ids.

Lesson 4: Asynchronous Apex

TypeUse it for
@futureSimple background work or callouts from a trigger
QueueableBackground jobs that need complex inputs, chaining or monitoring
Batch ApexProcessing very large numbers of records in chunks
Scheduled ApexRunning a job at a set time
Platform EventsPublishing events that other code or systems react to

Lesson 5: Testing and deployment

@IsTest
private class AccountServiceTest {
    @IsTest static void marksBigAccountsHot() {
        Account a = new Account(Name = 'Big Co', AnnualRevenue = 20000000);
        Test.startTest();
        AccountService.markVip(new List<Account>{ a });
        Test.stopTest();
        Assert.areEqual('Hot', a.Rating, 'Large accounts should be rated Hot');
    }
}
  • Production deployments need at least 75% code coverage overall, and every trigger needs some coverage; aim higher and test real outcomes with assertions.
  • Create test data in the test (or a @TestSetup method); tests don't see org data by default.
  • Test bulk cases (200 records), negative cases and different users with System.runAs().

Lesson 6: Classes and object-oriented Apex

Most real Apex lives in classes: services, trigger handlers, selectors and helpers. A few ideas make that code easy to read and test.

Access modifiers

  • private (the default): only inside the class.
  • protected: the class and classes that extend it.
  • public: any code in your namespace.
  • global: any code anywhere. Only for packages and web services, because it is hard to change later.

Static or instance?

static members belong to the class and are shared for the whole transaction, which is why a static Boolean can stop a trigger running twice. Instance members belong to one object created with new. Utility methods are usually static; anything holding state per job is usually an instance.

Constructors, interfaces and inheritance

public virtual class TriggerHandler {
  public virtual void beforeInsert(List<SObject> recs) {}
}
public class AccountHandler extends TriggerHandler {
  public override void beforeInsert(List<SObject> recs) { /* account logic */ }
}
public interface Notifier { void send(String message); }
public class EmailNotifier implements Notifier {
  public void send(String message) { /* send an email */ }
}
  • Methods can only be overridden if the parent marks them virtual or abstract; the child uses override.
  • An interface lists methods a class promises to have. It lets you swap implementations, for example a real notifier in production and a fake one in tests.
  • Constructors can call each other with this(...) (constructor chaining) to avoid repeating set-up code.

Custom exceptions

public class PaymentException extends Exception {}
// ...
if (amount <= 0) throw new PaymentException('Amount must be positive');

Class names must end with Exception. Throw them for business rule failures and catch them where you can show a clear message or log the error.

What changed in 2025–26

  • User mode (WITH USER_MODE, AccessLevel.USER_MODE) is now the standard way to respect field and object permissions in queries and DML. It replaces WITH SECURITY_ENFORCED.
  • The Assert class (Assert.areEqual, Assert.isTrue) is the modern way to write test assertions, with clearer messages than System.assertEquals.
  • Null coalescing (a ?? b) and the safe navigation operator (a?.b) shorten null checks.
  • Delayed Queueable jobs: System.enqueueJob(job, delayInMinutes) can wait up to 10 minutes, useful for retries. Transaction Finalizers handle failed Queueable jobs.
  • Apex cursors give a newer way to page through very large query results across transactions.
  • Database.queryWithBinds lets dynamic SOQL use bind variables, which prevents SOQL injection.

How this is asked in interviews

  • "How do you avoid governor limits?" Show the pattern: Set of Ids, one query, Map, one DML. See Apex questions.
  • "Future, Queueable or Batch?" Choose by data size and need, not definitions. See async Apex questions.
  • "Explain your trigger framework." One trigger per object, a handler, a bypass and a recursion guard. See trigger questions.
  • "User mode or with sharing?" With sharing covers records only; user mode also covers object and field access.
How to answer: Start with what you would do, say why, mention the limit or risk you are avoiding, and finish with a real example from a project or practice org. One clear minute beats five minutes of definitions.

Practise this topic

Common questions

01

Is Apex hard to learn?

If you know Java or C#, Apex will feel familiar. The new part is thinking in bulk and within governor limits, which is what interviewers test most.

02

Can I write Apex in a production org?

No. You write and test Apex in a sandbox or developer org and deploy it to production with tests.

03

Should I use Flow or Apex?

Use Flow for most business automation that admins should maintain. Use Apex for complex logic, high data volumes, advanced error handling and integrations.

Chat on WhatsApp