ApexSensei

Apex practice drills

A growing library of short Salesforce Apex exercises, grouped into modules. Each drill gives you a real task and starter code. You write the Apex and ApexSensei checks the result. Your first drills run right in the browser. Later drills run in a free Salesforce Developer org, which you connect once.

Pair these drills with a Salesforce practice exam when you are studying for Admin, Admin II, Platform Developer I, Platform Developer II, or Agentforce Specialist.

The first two modules are free to run. You can try the first 5 drills in Apex basics right on their page, with no account.

Start practicing free

Apex basics

Variables, numbers, text, dates, if and switch, loops, Lists, Sets and Maps. Your Apex foundation. beginner, free to run.

  1. Store the company name Beginner · 5 min

    A String holds text.

  2. Count open cases Beginner · 5 min

    An Integer is a whole number.

  3. Build the account label Beginner · 5 min

    The + operator joins text.

  4. Mark a high score Beginner · 5 min

    An if chooses one path.

  5. Return the tier you were given Beginner · 5 min

    return sends a value back to the caller.

  6. Comments that survive review Beginner · 5 min

    Comments explain code without changing what it does.

  7. Turn on the VIP flag Beginner · 5 min

    A Boolean holds only true or false.

  8. Set the monthly price Beginner · 5 min

    A Decimal holds a number with a decimal point, such as a price.

  9. Set the renewal date Beginner · 5 min

    A Date holds a calendar day.

  10. Pick the shipping fee Beginner · 5 min

    else if adds another test after an if.

  11. Put two regions in a list Beginner · 5 min

    A List<String> holds text values in order.

  12. Add up the seats Beginner · 5 min

    A for-each loop runs once for every item in a list: for (Integer seat : seats) { }.

  13. Hello, ApexSensei Beginner · 5 min

    Apex runs on Salesforce servers, so developers inspect values with System.debug().

  14. Quick win: double a number Beginner · 5 min

    A method takes input and gives back a value with return.

  15. Quick win: greet by name Beginner · 5 min

    + joins text together.

  16. Quick win: is it positive? Beginner · 5 min

    A comparison like n > 0 is already a Boolean: it is true or false.

  17. Quick win: make initials Beginner · 5 min

    Text has built-in methods.

  18. Quick win: pick the larger number Beginner · 5 min

    if runs a block only when its test is true.

  19. Quick win: shout it Beginner · 5 min

    toUpperCase() returns a new copy of the text in capital letters.

  20. Quick win: join a full name Beginner · 5 min

    When you join two variables you must add the glue yourself.

  21. Quick win: is the name blank? Beginner · 5 min

    Three things look empty to a user: null, '' and ' '.

  22. Integer division and Math.mod Beginner · 10 min

    Use Integer for whole counts.

  23. Money is a Decimal Beginner · 10 min

    Salesforce currency is a Decimal.

  24. True, false, and null Beginner · 12 min

    An empty number in Apex is null, not 0.

  25. Clean a Contact name Beginner · 12 min

    Apex String methods such as trim and capitalize turn messy imported text into clean names.

  26. Parse an email Beginner · 12 min

    indexOf and substring split an email address into the part before and after the @.

  27. Split and join text Beginner · 12 min

    split returns a List<String> and reads its argument as regex, so a real dot is '\\.'.

  28. Working with dates Beginner · 10 min

    Build a Date with Date.newInstance.

  29. If a Lead is hot Beginner · 12 min

    if / else if / else picks one answer from several, in order.

  30. Switch on Case status Beginner · 10 min

    switch on compares one value with a list of when branches and runs the first match.

  31. For loop: number invoices Beginner · 10 min

    A for loop has three parts: a start, a test, and a step.

  32. For-each over Accounts Beginner · 12 min

    A for-each loop walks every item in a List in order, with no index to manage: for (Account acct : accounts) { ...

  33. While a queue has work Beginner · 12 min

    A while loop repeats as long as its test is true.

  34. Lists of Opportunities Beginner · 15 min

    A List<Opportunity> keeps records in order: add puts one on the end, [i] reads position i starting at 0, and size() counts them.

  35. Maps: Id to Account Beginner · 15 min

    A Map<Id, Account> stores each Account under its Id.

  36. Remove duplicate emails with a Set Beginner · 12 min

    A Set<String> keeps each value only once.

  37. Count Leads by Rating with a Map Beginner · 15 min

    A Map<String, Integer> can keep a running count per key.

  38. Combine conditions with && and || Beginner · 10 min

    && is true only when both sides are true; || is true when either side is.

  39. Safe navigation with ?. Beginner · 12 min

    The ?. operator returns null instead of throwing when the value on its left is null.

  40. break and continue Beginner · 12 min

    continue skips the current loop iteration; break leaves the loop.

  41. Find the compile error Beginner · 10 min

    Apex refuses to run code that will not compile.

  42. Group records in a Map<String, List<Contact>> Beginner · 12 min

    A Map<String, List<Contact>> groups records by a shared field.

  43. Convert text to Integer, safely Beginner · 12 min

    Integer.valueOf(text) returns the number inside text, but throws on null, empty or non-numeric.

Classes & objects

Classes, constructors, methods, access modifiers, exceptions and enums. beginner, free to run.

  1. Build a Case summary class Beginner · 10 min

    A class groups fields and methods, and new builds a separate object for each case.

  2. Build queue labels with parameters Beginner · 10 min

    Parameters make one method reusable.

  3. Return a value and record work Beginner · 12 min

    A method's return type promises a value back to the caller.

  4. Initialize a service appointment Beginner · 12 min

    A constructor runs when new builds an object, so every new object starts with a valid state.

  5. Protect a support ticket subject Beginner · 12 min

    private fields plus public methods let the class enforce its own rules.

  6. Expose a read-only quote total Intermediate · 15 min

    Apex properties expose a value through get and set, and a getter-only property returns a derived value.

  7. Overload a Case label method Intermediate · 15 min

    Overloading is one method name with different parameter lists; Apex picks the version whose parameters match your call.

  8. Route Cases with an enum Intermediate · 15 min

    An enum is a type with a fixed set of named values.

  9. Recover from division by zero Intermediate · 15 min

    try holds code that might fail; a matching catch runs instead if it does, and later code still runs.

  10. Reject an invalid discount Intermediate · 18 min

    A custom exception gives a business rule its own type.

  11. Interface with two implementations Beginner · 14 min

    An interface is a contract: method signatures with no bodies.

  12. virtual, override and super Intermediate · 18 min

    A virtual method can be replaced by a subclass marked override, and super.method() runs the base version from inside the override.

  13. Constructor chaining with this(...) Intermediate · 14 min

    A class can have several constructors.

  14. finally and several catch blocks Intermediate · 14 min

    A try block can be followed by several catch blocks, one per exception type, and a finally block that runs no matter what.

  15. Static versus instance members Intermediate · 16 min

    static members belong to the class and are shared across every instance for the whole transaction.

  16. Extend an abstract score rule Intermediate · 16 min

    An abstract class can hold shared methods and leave one or more methods for a subclass to finish with override.

SOQL queries

SOQL and SOSL: filters, bind variables, relationships, aggregates, date literals and safe dynamic queries. intermediate, run with Apex Path.

  1. Query one Account Beginner · 8 min

    SOQL reads Salesforce records into Apex.

  2. Filter Account names Beginner · 12 min

    WHERE keeps rows that meet a condition.

  3. Rank practice Accounts Beginner · 10 min

    ORDER BY sets the result order and LIMIT caps the row count.

  4. Bind an Account name Beginner · 12 min

    A bind variable puts an Apex value into SOQL with :variable.

  5. Match an Account list Beginner · 12 min

    IN :collection matches any value in a Set or List.

  6. Find missing Contact emails Beginner · 12 min

    SOQL uses = null and != null to find fields that are empty or filled in.

  7. Read a Contact's Account Intermediate · 14 min

    A child-to-parent query uses dot notation.

  8. Load Account Contacts Intermediate · 15 min

    A parent-to-child subquery pulls Accounts and their Contacts in one SOQL.

  9. Find Accounts by Contact Intermediate · 15 min

    A semi-join (Id IN (SELECT AccountId FROM Contact ...)) keeps parent rows that have a matching child.

  10. Summarize Opportunity amounts Intermediate · 15 min

    COUNT() counts rows and must sit alone in its SELECT.

  11. Keep busy Account groups Intermediate · 18 min

    GROUP BY returns one row per value.

  12. Stream tagged Accounts Intermediate · 15 min

    A SOQL for loop puts the query right in the loop header.

  13. Search safely with dynamic SOQL Intermediate · 18 min

    Dynamic SOQL that glues in user input lets a quote rewrite the query.

  14. Filter with date literals Intermediate · 18 min

    SOQL date literals (TODAY, NEXT_N_DAYS:30, LAST_N_DAYS:30) are evaluated at query time in the user's time zone.

  15. Search names with SOSL Intermediate · 18 min

    SOSL searches text across several objects at once and returns one list per object, in the order you wrote after RETURNING.

  16. Single-row query: zero or many rows Intermediate · 13 min

    A SOQL query that assigns straight into an sObject throws when the match count is 0 or more than 1.

  17. WITH USER_MODE versus system mode Intermediate · 13 min

    Apex SOQL runs in system mode by default.

  18. Group by a parent field Intermediate · 14 min

    GROUP BY <field> collapses rows that share a value into one summary row.

  19. Multi-level relationships with __r Intermediate · 14 min

    Dot notation walks lookup fields in the SELECT.

  20. Paging with LIMIT and last-value Intermediate · 15 min

    LIMIT caps rows per page.

DML operations

Insert, update, upsert and delete, Database methods, save results, savepoints and bulk-safe DML. intermediate, run with Apex Path.

  1. SObject field access Beginner · 8 min

    Use dot notation when you know the field while you write the code.

  2. Insert a tagged Account Beginner · 10 min

    insert saves a new record and writes the new Id back onto the same variable.

  3. Update a tagged Account Beginner · 12 min

    update saves changed fields on a record that already has an Id.

  4. Delete challenge-created records Intermediate · 12 min

    delete removes records by Id.

  5. Bulk update once Intermediate · 15 min

    Bulk-safe Apex changes records inside a loop and saves them all with one DML after the loop.

  6. Upsert: insert or update Intermediate · 15 min

    upsert inserts when no match exists and updates when one does.

  7. Handle Database.SaveResult Intermediate · 15 min

    Database.insert(records, false) turns on partial success: it returns one SaveResult per record instead of throwing.

  8. Savepoint and rollback Intermediate · 15 min

    A savepoint marks a spot in the current transaction; Database.rollback undoes every DML made after it, with no Recycle Bin trace.

  9. Insert an Account with Contacts Intermediate · 18 min

    A child record needs its parent's Id, so the parent Account is inserted before its Contacts.

  10. Catch a DmlException and read its details Intermediate · 14 min

    Default DML is all-or-none, so one bad row throws DmlException.

  11. Undelete from the Recycle Bin Intermediate · 12 min

    delete moves a row to the Recycle Bin; undelete restores it with the same Id.

  12. Roll back parent and children on a child failure Intermediate · 15 min

    One savepoint before the first DML, one rollback inside the catch, and the whole step vanishes.

  13. Merge duplicate Accounts Intermediate · 14 min

    Database.merge(master, duplicate) keeps the master, deletes the duplicate, and moves related children to the master.

Unit testing

Apex test classes that fail when the code is wrong: assertions, test data, mocks and callout mocks. intermediate, run with Apex Path.

  1. Assert service outcomes Beginner · 10 min

    A test needs an expected value to compare with the real result.

  2. Create isolated test data Beginner · 12 min

    A test should create the records it needs.

  3. Build a test data factory Intermediate · 12 min

    A test data factory is a public @IsTest class with helpers that build records for many tests.

  4. Test success and exceptions Intermediate · 15 min

    Test the happy path and the error path.

  5. Check partial DML results Intermediate · 15 min

    Database.insert(rows, false) returns one SaveResult per row.

  6. Reset limits around the act Intermediate · 15 min

    Test.startTest() gives the code under test a fresh set of governor limits.

  7. Prove bulk behavior Intermediate · 15 min

    Bulk tests use real batch sizes, like 200 records, and check every result.

  8. Use a fake collaborator Intermediate · 18 min

    extends makes your class a child; override replaces a parent method marked virtual.

  9. Mock an HTTP callout Intermediate · 16 min

    Tests cannot make real HTTP callouts.

  10. Share setup and run as another user Intermediate · 18 min

    @TestSetup runs once per class, and every test method sees its rows.

Triggers

Before and after triggers, handler classes, bulk patterns, recursion guards and roll-ups. intermediate, run with Apex Path.

  1. Write your first before-insert trigger Beginner · 10 min

    A before insert trigger sees new records in Trigger.new before Salesforce saves them.

  2. Create follow-up Tasks after Contact insert Intermediate · 15 min

    Use after insert when related records need the new records' Ids.

  3. React to a Contact email change Intermediate · 15 min

    An update trigger sees the new record in Trigger.new and the saved one in Trigger.oldMap, keyed by Id.

  4. Route Case trigger contexts Intermediate · 15 min

    One trigger can handle several events.

  5. Mark parent Accounts in bulk Intermediate · 18 min

    A bulk-safe trigger handler collects parent Ids first and runs one query and one update for the whole batch.

  6. Move Opportunity logic to a handler Intermediate · 15 min

    A trigger should pick the event; a handler class should do the work.

  7. Require a Contact email domain Intermediate · 18 min

    A before-trigger handler can reject a single record with a field-level addError.

  8. Stop recursive Account updates Advanced · 20 min

    A static variable keeps its value for the whole transaction, so a static Set<Id> can remember which records a trigger already handled.

  9. Block deleting Accounts with open deals Advanced · 20 min

    A delete trigger has no Trigger.new; the records are in Trigger.old and keyed by Id in Trigger.oldMap.

  10. Keep a Contact count on Account Advanced · 25 min

    A rollup counts child rows on a parent by running one aggregate query, not by adding or subtracting 1 per event.

  11. Create a child record only when a field changes Intermediate · 18 min

    In an after update trigger, compare the new value to the old value from Trigger.oldMap before you create a child record.

Asynchronous Apex

Future methods, Queueable, Batch and Schedulable Apex. advanced, run with Apex Path.

  1. Complete a Contact review in the future Intermediate · 15 min

    A @future method runs later, in its own transaction.

  2. Carry Account work in a Queueable Intermediate · 18 min

    A Queueable job keeps state in its fields and runs execute later, outside the current transaction.

  3. Build a Batch lifecycle Advanced · 20 min

    Batch Apex splits a big job into chunks.

  4. Keep counts across Batch transactions Advanced · 25 min

    start, each execute and finish run in separate transactions.

  5. Schedule an Account review Advanced · 22 min

    Schedulable Apex runs execute at times set by a cron string.

  6. Make a Queueable retry idempotent Advanced · 25 min

    A retry is idempotent when running it twice has the same effect as once.

  7. Chain a second Queueable Advanced · 20 min

    A Queueable can start another Queueable with System.enqueueJob.

  8. Attach a Queueable Finalizer Advanced · 22 min

    A Queueable can also implement Finalizer.

  9. Publish a Platform Event Beginner · 10 min

    A Platform Event is a named message, not a row you query later.

Debugging

Fix real production bugs: queries and DML in loops, null checks, recursion, mixed DML, empty tests and batch state. intermediate, run with Apex Path.

  1. Fix a missing null check Beginner · 10 min

    Calling a method on a blank field throws Attempt to de-reference a null object.

  2. Fix a query that finds no rows Beginner · 10 min

    Assigning a query to one record throws when nothing matches.

  3. Fix a query inside a loop Intermediate · 15 min

    Too many SOQL queries: 101 is the classic production failure.

  4. Fix DML inside a loop Intermediate · 15 min

    Every insert, update or delete statement counts against the limit of 150 per transaction.

  5. Fix a test that checks nothing Intermediate · 15 min

    A test passes when nothing throws.

  6. Stop a trigger calling itself Advanced · 15 min

    maximum trigger depth exceeded means a trigger caused DML that ran the same trigger, sixteen times.

  7. Fix a mixed DML error Advanced · 20 min

    A User with a role cannot share a transaction with Account.

  8. Fix a Batch job that forgets its count Advanced · 20 min

    Each execute and finish runs in its own transaction on a fresh copy of the class.

Security & deployment

Governor limits, security and the habits that survive a production deploy. advanced, run with Apex Path.

  1. Measure governor headroom Intermediate · 10 min

    Governor limits cap what one transaction can use, such as 100 SOQL queries.

  2. Build Contacts with one query and one insert Intermediate · 18 min

    A query inside a loop costs one SOQL query per record, and a transaction allows only 100.

  3. Gate a release with test evidence Intermediate · 18 min

    A release gate fails closed: missing evidence counts as a failure.

  4. Build a secure Account service Advanced · 25 min

    Saved Apex runs in system mode and ignores user access unless you check.

  5. User-mode DML with `insert as user` Intermediate · 15 min

    insert as user <rows>; runs DML in user mode: field-level security and sharing apply, and a disallowed field throws SecurityException.

  6. Gate work behind a feature flag Intermediate · 12 min

    A feature flag turns a behavior on without a new deploy.

  7. Choose a deploy test level Beginner · 10 min

    A deploy to production must run tests.