LearnFrenzy
Sign in Take a free test

Salesforce Apex interview · Set 1 of 7

Apex Basics: Data Types, Collections, SOQL and DML

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

The Apex foundations every interview checks

Know your collections, write efficient SOQL with relationships, choose the right DML style, and enforce security by default. Everything else in Apex builds on these.

  • DataTypes, List, Set and Map patterns.
  • QueriesSOQL, SOSL and relationship queries.
  • SafetyDML options, sharing and user mode.

Every Salesforce developer interview begins here: how Apex stores data, how you query records and how you save them. Interviewers expect you to know the collection types cold and to write SOQL that respects limits and security from the first line.

1. What is Apex and where does it run?

Apex is Salesforce's strongly typed, object-oriented language with Java-like syntax. It runs on Salesforce's multi-tenant servers, so the platform enforces governor limits to keep one org from hogging shared resources. Apex runs in triggers, classes called from Flows and LWC, scheduled and batch jobs, web services and anonymous scripts.


2. List, Set and Map — when do you use each?

List — ordered, allows duplicates, index access (query results). Set — unique values, fast contains() (collecting Ids). Map — key → value lookups (record by Id). The constructor new Map<Id, Account>(listOfAccounts) builds an Id map in one line — a pattern you use in almost every trigger.

List<Account> accounts = [SELECT Id, Name FROM Account WHERE Industry = 'Education' LIMIT 200];

Set<Id> accountIds = new Set<Id>();
for (Account a : accounts) accountIds.add(a.Id);

Map<Id, Account> accountsById = new Map<Id, Account>(accounts);   // Id → record in one line
Account first = accountsById.get(accounts[0].Id);

3. SOQL vs SOSL?

SOQL queries one object (plus related objects) with precise filters — like SQL SELECT. SOSL searches text across many objects at once using the search index — like a search box. Use SOQL when you know the object and fields; SOSL when you search for a term (a phone number or name) across Accounts, Contacts and Leads.

List<Contact> contacts = [SELECT Id, Name, Email FROM Contact WHERE Email LIKE '%@learnfrenzy.com'];

List<List<SObject>> results = [FIND 'Asha*' IN NAME FIELDS
                               RETURNING Contact(Id, Name), Lead(Id, Name, Company)];
List<Contact> foundContacts = (List<Contact>) results[0];

4. How do relationship queries work in SOQL?

Child-to-parent: use dot notation on the lookup (Account.Name, or Custom__r.Field__c for custom relationships). Parent-to-child: a subquery using the child relationship name (Contacts, or Children__r). One query replaces many, which is essential for staying within limits.

List<Account> accounts = [
    SELECT Id, Name,
           (SELECT Id, LastName, Email FROM Contacts WHERE Email != null),   // parent → child
           Owner.Name                                                        // child → parent
    FROM Account
    WHERE CreatedDate = LAST_N_DAYS:30
];
for (Account a : accounts) {
    for (Contact c : a.Contacts) System.debug(a.Name + ' → ' + c.LastName);
}

5. DML statements vs Database methods?

DML statements (insert, update…) are all-or-nothing: one bad record throws an exception and rolls back the whole operation. Database.insert(records, false) allows partial success and returns results you can inspect per record — useful for data loads where some rows may fail.

List<Database.SaveResult> results = Database.insert(newLeads, false);   // allOrNone = false
for (Integer i = 0; i < results.size(); i++) {
    if (!results[i].isSuccess()) {
        for (Database.Error e : results[i].getErrors()) {
            System.debug('Lead ' + i + ' failed: ' + e.getStatusCode() + ' - ' + e.getMessage());
        }
    }
}

6. What do with sharing, without sharing and inherited sharing mean?

with sharing enforces the running user's record-level sharing; without sharing ignores it (system context); inherited sharing takes the caller's mode and defaults to with sharing when called directly — the safest choice for reusable classes. Sharing keywords do not enforce object or field permissions; use user mode for that.


7. How do you enforce object and field security in Apex?

Run queries and DML in user mode: WITH USER_MODE in SOQL and AccessLevel.USER_MODE for DML — they respect CRUD, field-level security and sharing. Security.stripInaccessible() removes fields the user cannot see from records. WITH SECURITY_ENFORCED is the older option.

List<Opportunity> opps = [SELECT Id, Name, Amount FROM Opportunity WHERE IsClosed = false WITH USER_MODE];

Database.insert(newCases, AccessLevel.USER_MODE);

SObjectAccessDecision decision = Security.stripInaccessible(AccessType.READABLE, opps);
List<Opportunity> safe = (List<Opportunity>) decision.getRecords();

8. What are static resources, custom labels and custom metadata used for in Apex?

Custom Labels hold translatable text (System.Label.Welcome_Message). Custom Metadata Types hold configuration that deploys with your code and can be queried without counting against SOQL limits in many cases — ideal for rules, mappings and feature switches instead of hard-coded values. Static resources hold files such as JSON or images.

for (Discount_Rule__mdt rule : Discount_Rule__mdt.getAll().values()) {
    if (rule.Is_Active__c && order.Amount >= rule.Min_Amount__c) {
        order.Discount__c = rule.Percent__c;
    }
}

Remember

Key points

  • Map<Id, SObject>(list)

    Build Id lookups in one line.

  • One query with relationships

    Instead of queries inside loops.

  • allOrNone = false

    For partial-success data loads.

  • Sharing ≠ FLS

    Use WITH USER_MODE for both.

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 What is the difference between Id and String for record ids? Basic

    The Id type validates 15/18-character Salesforce ids and compares them correctly; a String does not. Use Id for record ids.

  2. 2 What is an SObject? Basic

    The generic type for any Salesforce record (Account, Case, Custom__c). You can work with fields dynamically via record.get('Name') and record.put().

  3. 3 How do you write a dynamic SOQL query safely? Intermediate

    Use Database.queryWithBinds() with a bind map, or escape user input with String.escapeSingleQuotes() and allow-list field names — never concatenate raw input.

  4. 4 What is the difference between upsert and merge? Intermediate

    Upsert inserts or updates using Id or an external id field. Merge combines up to three duplicate records of the same object into one, re-parenting related records.

  5. 5 What does FOR UPDATE do in SOQL? Advanced

    It locks the returned records for the transaction so other processes cannot update them at the same time — preventing race conditions on counters or balances.

  6. 6 What are aggregate queries? Basic

    SOQL with COUNT, SUM, AVG, MIN, MAX and GROUP BY returning AggregateResult rows, read with ar.get('expr0') or an alias.

Preparing with friends?

Share this page with your study group or placement batch.

Search LearnFrenzy

Esc

Quick links