LearnFrenzy
Sign in Take a free test

Salesforce Apex interview · Set 6 of 7

Apex Coding Interview Questions (Scenarios with Code)

  • 6 follow-up questions
  • 4 key points
  • Code examples
Test yourself

Scenario coding, done the professional way

Every solution follows the same discipline: collect Ids, query once, use maps, act only on real changes, and DML once. Say that pattern out loud before coding.

  • TriggersRoll-ups, duplicates, tasks and syncing.
  • QueriesAggregates, grouping and offsets.
  • AutomationBatch jobs and Flow invocable actions.

Salesforce developer interviews almost always include a live coding scenario: “write a trigger that…”. Each solution below is bulk-safe, follows the handler style where it matters, and comes with the reasoning you should say out loud.

1. Keep a count of Contacts on each Account (insert, update, delete, undelete).

Collect affected Account Ids — including the old Account when a contact moves — then recount with one aggregate query and update the Accounts once.

trigger ContactCount on Contact (after insert, after update, after delete, after undelete) {
    Set<Id> accountIds = new Set<Id>();
    for (Contact c : Trigger.isDelete ? Trigger.old : Trigger.new) {
        if (c.AccountId != null) accountIds.add(c.AccountId);
    }
    if (Trigger.isUpdate) {
        for (Contact c : Trigger.old) if (c.AccountId != null) accountIds.add(c.AccountId);
    }
    if (accountIds.isEmpty()) return;

    Map<Id, Integer> counts = new Map<Id, Integer>();
    for (Id accId : accountIds) counts.put(accId, 0);
    for (AggregateResult ar : [SELECT AccountId accId, COUNT(Id) total FROM Contact
                               WHERE AccountId IN :accountIds GROUP BY AccountId]) {
        counts.put((Id) ar.get('accId'), (Integer) ar.get('total'));
    }
    List<Account> updates = new List<Account>();
    for (Id accId : counts.keySet()) updates.add(new Account(Id = accId, Contact_Count__c = counts.get(accId)));
    update updates;
}

2. Prevent duplicate Contacts with the same email.

Check duplicates both inside the incoming batch and against existing records, in a before trigger with addError. (In real orgs, Duplicate Rules may be preferable — mention it.)

trigger ContactDuplicateEmail on Contact (before insert, before update) {
    Map<String, Contact> incoming = new Map<String, Contact>();
    for (Contact c : Trigger.new) {
        if (String.isBlank(c.Email)) continue;
        String key = c.Email.toLowerCase();
        if (incoming.containsKey(key)) c.Email.addError('Duplicate email in this batch.');
        else incoming.put(key, c);
    }
    for (Contact existing : [SELECT Id, Email FROM Contact WHERE Email IN :incoming.keySet()]) {
        Contact c = incoming.get(existing.Email.toLowerCase());
        if (c != null && c.Id != existing.Id) c.Email.addError('A contact with this email already exists.');
    }
}

3. When an Opportunity becomes Closed Won, create a follow-up Task for its owner — once.

After update trigger; compare with the old stage so a later edit does not create a second task.

trigger OppFollowUp on Opportunity (after update) {
    List<Task> tasks = new List<Task>();
    for (Opportunity o : Trigger.new) {
        Opportunity old = Trigger.oldMap.get(o.Id);
        if (o.StageName == 'Closed Won' && old.StageName != 'Closed Won') {
            tasks.add(new Task(WhatId = o.Id, OwnerId = o.OwnerId, Subject = 'Onboarding call',
                               Priority = 'High', ActivityDate = Date.today().addDays(3)));
        }
    }
    if (!tasks.isEmpty()) insert tasks;
}

4. Copy the Account's phone to all its Contacts when the Account phone changes.

After update on Account; query related Contacts of only changed Accounts in one query, then one update.

trigger AccountPhoneSync on Account (after update) {
    Map<Id, Account> changed = new Map<Id, Account>();
    for (Account a : Trigger.new) {
        if (a.Phone != Trigger.oldMap.get(a.Id).Phone) changed.put(a.Id, a);
    }
    if (changed.isEmpty()) return;
    List<Contact> contacts = [SELECT Id, AccountId FROM Contact WHERE AccountId IN :changed.keySet()];
    for (Contact c : contacts) c.Phone = changed.get(c.AccountId).Phone;
    update contacts;
}

5. Group Opportunities by Stage and return the total amount per stage.

Use an aggregate query rather than looping in Apex — the database does the work.

public static Map<String, Decimal> totalsByStage() {
    Map<String, Decimal> totals = new Map<String, Decimal>();
    for (AggregateResult ar : [SELECT StageName stage, SUM(Amount) total FROM Opportunity
                               WHERE IsClosed = false WITH USER_MODE GROUP BY StageName]) {
        totals.put((String) ar.get('stage'), (Decimal) ar.get('total'));
    }
    return totals;
}

6. Write a method that returns the second-highest Opportunity amount.

Let SOQL sort and skip — no Apex loops needed. Handle the case where there is no second record.

public static Decimal secondHighestAmount() {
    List<AggregateResult> rows = [SELECT Amount amt FROM Opportunity WHERE Amount != null
                                  GROUP BY Amount ORDER BY Amount DESC LIMIT 1 OFFSET 1];
    return rows.isEmpty() ? null : (Decimal) rows[0].get('amt');
}

7. Reassign all open Cases of deactivated users to a queue (batch).

A batch job keeps it within limits for any data volume; the queue Id comes from a query, not a hard-coded value.

public class ReassignOrphanCases implements Database.Batchable<SObject> {
    public Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator([SELECT Id, OwnerId FROM Case
            WHERE IsClosed = false AND Owner.IsActive = false]);
    }
    public void execute(Database.BatchableContext bc, List<Case> scope) {
        Id queueId = [SELECT Id FROM Group WHERE Type = 'Queue' AND DeveloperName = 'Support_Unassigned' LIMIT 1].Id;
        for (Case c : scope) c.OwnerId = queueId;
        update scope;
    }
    public void finish(Database.BatchableContext bc) {}
}

8. Write an invocable method that Flow can call to calculate a discount.

Invocable methods take and return lists so Flow can call them in bulk; label and describe every variable.

public with sharing class DiscountAction {
    public class Request {
        @InvocableVariable(required=true label='Order Amount') public Decimal amount;
        @InvocableVariable(label='Customer Tier') public String tier;
    }
    public class Result {
        @InvocableVariable(label='Discount Percent') public Decimal percent;
    }
    @InvocableMethod(label='Calculate Discount' description='Returns the discount percent for an order amount and customer tier')
    public static List<Result> calculate(List<Request> requests) {
        List<Result> out = new List<Result>();
        for (Request r : requests) {
            Result res = new Result();
            res.percent = r.tier == 'Gold' ? 15 : (r.amount >= 50000 ? 10 : 0);
            out.add(res);
        }
        return out;
    }
}

Remember

Key points

  • Handle all four events

    Insert, update, delete and undelete for roll-ups.

  • Old parent matters

    Recount the account a contact moved from.

  • Let SOQL aggregate

    Instead of Apex loops.

  • No hard-coded Ids

    Query queues and record types by name.

Interview drill

Follow-up questions

What the interviewer asks after your first answer. Turn on practice mode, answer each one aloud, then reveal.

  1. 1 Why not use a roll-up summary field for the contact count? Basic

    Roll-up summary fields work only on master-detail relationships; Account–Contact is a lookup, so you need Apex, a Flow, or a tool like DLRS.

  2. 2 How would you write the duplicate check without a trigger? Basic

    Use a Matching Rule and a Duplicate Rule set to block — no code, works for UI and API.

  3. 3 How do you test the contact count trigger? Intermediate

    Insert contacts under two accounts, move one, delete one, undelete it, and assert the counts after each step, plus a 200-record bulk test.

  4. 4 Your trigger must call an external API. What changes? Intermediate

    Callouts are not allowed from triggers synchronously; enqueue a Queueable with Database.AllowsCallouts and pass record Ids.

  5. 5 How would you make a field mandatory only for a certain stage? Basic

    A validation rule such as AND(ISPICKVAL(StageName, 'Negotiation'), ISBLANK(Next_Step__c)) — no code needed.

  6. 6 How do you get record type Ids without SOQL? Intermediate

    Schema.SObjectType.Account.getRecordTypeInfosByDeveloperName().get('Partner').getRecordTypeId().

Preparing with friends?

Share this page with your study group or placement batch.

Search LearnFrenzy

Esc

Quick links