Skip to content
ReadMe Daily

Search articles, problems, patterns and every cheat sheet topic.

Salesforce Cheat Sheet

10 groups · 43 topics · Updated

Salesforce is a cloud platform for customer data that you configure with clicks and extend with code. This is an independent guide written in November 2026. Limits and commands change between releases, so confirm them on the official pages linked at the end.

1

Data model

How Salesforce stores data, and what things are called.

Key terms

Term Meaning Like
Org One company's copy of Salesforce A database
Object A kind of thing: Account, Invoice A table
Field One piece of data on an object A column
Record One saved item A row
App A set of tabs for one job A workspace

Standard objects

Object Holds
Account A company or organisation
Contact A person at an account
Lead A possible customer, not yet qualified
Opportunity A deal in progress
Case A support request
User Someone who can log in
Task, Event To-dos and meetings

API names

The name code uses. The suffix says what kind of thing it is.

Suffix Means
__c Custom object or field
__r Custom relationship, used in queries
__mdt Custom metadata type
__e Platform event
ns__ (prefix) Belongs to a managed package
Invoice__c            a custom object
Invoice__c.Total__c   a custom field
Invoice__r.Total__c   reached from a child

Relationships

Lookup Master-detail
Parent required No Yes
Delete the parent Child stays Children are deleted
Owner and sharing Its own Taken from the parent
Roll-up summary No Yes
  • Many-to-many: a junction object with two master-detail fields.

Record IDs

  • 15 characters: case-sensitive. 18 characters: safe where case is ignored, such as Excel.
  • The first three characters tell you the object.
Prefix Object
001 Account
003 Contact
00Q Lead
006 Opportunity
500 Case
005 User
2

SOQL

The query language for reading records.

Basic query

SELECT Id, Name, Industry
FROM Account
WHERE Industry = 'Banking'
ORDER BY Name
LIMIT 10
  • There is no SELECT *. Name the fields.
  • Text goes in single quotes.

Filters

WHERE Amount > 1000 AND IsClosed = false
WHERE Name LIKE 'Acme%'
WHERE StageName IN ('New', 'Won')
WHERE Phone != null
WHERE CreatedDate = LAST_N_DAYS:30
WHERE CloseDate = THIS_MONTH
Date literal Means
TODAY, YESTERDAY That day
THIS_WEEK, THIS_MONTH, THIS_YEAR The current period
LAST_N_DAYS:n The past n days
NEXT_N_DAYS:n The coming n days

Parent fields

From a child up to its parent: use a dot.

SELECT LastName, Account.Name
FROM Contact
 
SELECT Name, Invoice__r.Total__c
FROM Line__c
  • Standard: the relationship name, Account.
  • Custom: swap __c for __r.

Child records

From a parent down to its children: a query inside brackets.

SELECT Name,
  (SELECT LastName FROM Contacts)
FROM Account
  • Use the child relationship name, usually the plural: Contacts, Opportunities.
  • Custom children end in __r: Lines__r.

Totals and groups

SELECT StageName, COUNT(Id), SUM(Amount)
FROM Opportunity
GROUP BY StageName
HAVING SUM(Amount) > 10000
Function Gives
COUNT() Number of rows
SUM(), AVG() Total, average
MIN(), MAX() Smallest, largest
FIND 'acme*' IN NAME FIELDS
RETURNING Account(Name), Contact(Name)
SOQL SOSL
Searches One object and its relatives Many objects at once
Best for Exact conditions Finding a word anywhere
Returns Records A list of lists
3

Apex basics

Salesforce's programming language: similar to Java, and it runs on the server.

Variables

Integer count = 5;
Decimal price = 19.99;
String name = 'Asha';
Boolean active = true;
Date today = Date.today();
Account acc = new Account(Name = 'Acme');
  • Statements end with ;. Text uses single quotes.
  • Names are not case-sensitive.
  • A variable with no value is null.

Collections

List<String> names = new List<String>();
names.add('Asha');
names[0];           // → 'Asha'
names.size();       // → 1
 
Set<Id> ids = new Set<Id>();
ids.contains(acc.Id);
 
Map<Id, Account> byId =
    new Map<Id, Account>(accounts);
byId.get(acc.Id);
Type Holds
List Items in order, repeats allowed
Set Unique items, no order
Map Values looked up by key

Query in Apex

String industry = 'Banking';
 
List<Account> accounts = [
    SELECT Id, Name
    FROM Account
    WHERE Industry = :industry
];
  • Square brackets run SOQL and return a list.
  • :industry inserts a variable safely.
  • A field you did not select cannot be read.

Save records (DML)

insert acc;
update accounts;
upsert accounts External_Id__c;
delete acc;
undelete acc;
// keep going if some records fail
Database.insert(accounts, false);
  • Pass a list, not one record at a time.

A class

public with sharing class AccountService {
 
    public static void rename(
        Id accountId, String newName
    ) {
        Account acc = new Account(
            Id = accountId,
            Name = newName
        );
        update acc;
    }
}
Keyword Record access
with sharing Only what the user may see
without sharing Everything
inherited sharing Same as the code that called it

Use with sharing unless you have a reason not to.

Nulls and errors

String city = acc?.BillingCity;
String label = city ?? 'Unknown';
 
try {
    update acc;
} catch (DmlException e) {
    System.debug(e.getMessage());
}
  • ?. gives null instead of an error when the left side is null.
  • ?? supplies a value when the left side is null.
4

Triggers and async

Code that runs when records are saved, and code that runs later.

A trigger

trigger AccountTrigger on Account (
    before insert, before update
) {
    for (Account a : Trigger.new) {
        if (a.Phone == null) {
            a.addError('Phone is required');
        }
    }
}
  • One trigger per object. Keep the logic in a class and call it from here.

Trigger context

Variable Holds
Trigger.new The records being saved
Trigger.old The records as they were
Trigger.newMap The new records by Id
Trigger.oldMap The old records by Id
Trigger.isInsert True for an insert
Trigger.isBefore True before the save
  • Trigger.old is empty on insert. Trigger.new is empty on delete.

Before or after

Use When you need to
before Change or check the record being saved. No DML needed
after Use the record's Id, or change other records

Bulkify

A trigger receives up to 200 records at once. Never query or save inside a loop.

// Bad: one query per record
for (Contact c : Trigger.new) {
    Account a = [SELECT Name FROM Account
                 WHERE Id = :c.AccountId];
}
// Good: one query for all records
Set<Id> ids = new Set<Id>();
for (Contact c : Trigger.new) {
    ids.add(c.AccountId);
}
Map<Id, Account> accounts =
    new Map<Id, Account>([
        SELECT Name FROM Account
        WHERE Id IN :ids
    ]);

Run it later

Tool Use it for
@future A simple job or callout after the save
Queueable The same, with objects as input and chaining
Batch Apex Thousands or millions of records, in chunks
Schedulable Running at a set time
System.enqueueJob(new SyncJob(ids));
Database.executeBatch(new CleanUp(), 200);
System.schedule(
    'Nightly', '0 0 2 * * ?', new CleanUp()
);
5

Governor limits

Caps that stop one piece of code from hogging the shared servers.

Per transaction

Limit Normal Async
SOQL queries 100 200
Rows returned by SOQL 50,000 50,000
SOSL searches 20 20
DML statements 150 150
Rows changed by DML 10,000 10,000
CPU time 10 s 60 s
Heap (memory) 6 MB 12 MB
Callouts 100 100

Going over throws a LimitException, which cannot be caught. The whole transaction is undone.

Stay within limits

  • Query and save outside loops.
  • Work on lists, sets and maps, not single records.
  • Select only the fields you need, and filter with WHERE.
  • Move heavy work to Batch Apex or a Queueable.
  • One trigger per object, so the work is not repeated.

Check usage

Limits.getQueries();       // used so far
Limits.getLimitQueries();  // the cap
Limits.getDmlStatements();
Limits.getCpuTime();
Limits.getHeapSize();
6

Testing

Salesforce will not deploy Apex to production without tests.

A test class

@isTest
private class AccountServiceTest {
 
    @isTest
    static void renamesAccount() {
        Account a = new Account();
        a.Name = 'Old';
        insert a;
 
        Test.startTest();
        AccountService.rename(a.Id, 'New');
        Test.stopTest();
 
        a = [SELECT Name FROM Account
             WHERE Id = :a.Id];
        Assert.areEqual('New', a.Name);
    }
}

The rules

  • At least 75% of your Apex must be covered by tests to deploy to production.
  • Every trigger needs some coverage.
  • Tests cannot see the org's real records. Create the data you need.
  • Changes made by a test are undone when it ends.

Useful tools

Tool Does
@TestSetup Creates data once for every test in the class
Test.startTest() Gives the code under test fresh limits
Test.stopTest() Makes async work finish before the checks
Assert.areEqual(a, b) Fails unless the two are equal
Assert.isTrue(x) Fails unless x is true
System.runAs(user) Runs as another user
  • Test with 200 records, not one, to prove the code is bulk-safe.
  • Check results. Coverage with no assertions proves nothing.
7

Lightning Web Components

The current way to build user interface on Salesforce, with standard HTML and JavaScript.

Files

lwc/
  helloWorld/
    helloWorld.html          template
    helloWorld.js            logic
    helloWorld.js-meta.xml   where it shows
    helloWorld.css           optional
  • The folder and files share one name, starting with a lowercase letter.
  • In markup it becomes <c-hello-world>.

A component

<template>
  <p>Hello, {name}</p>
  <lightning-button
    label="Greet"
    onclick={handleClick}>
  </lightning-button>
</template>
import { LightningElement } from 'lwc';
 
export default class HelloWorld
  extends LightningElement {
  name = 'Asha';
 
  handleClick() {
    this.name = 'World';
  }
}
  • {name} shows a property. Changing it redraws the template.

Decorators

Decorator Makes a property
@api Public: a parent or the page can set it
@wire Filled with Salesforce data automatically
@track Watched deep inside an object or array. Rarely needed
@api recordId; // set on a record page

Show and repeat

<template lwc:if={hasItems}>
  <template for:each={items} for:item="it">
    <p key={it.Id}>{it.Name}</p>
  </template>
</template>
<template lwc:else>
  <p>Nothing to show</p>
</template>
  • Every repeated element needs a unique key.

Call Apex

public with sharing class AcctCtrl {
    @AuraEnabled(cacheable=true)
    public static List<Account> getList() {
        return [SELECT Id, Name
                FROM Account LIMIT 10];
    }
}
import getList from
  '@salesforce/apex/AcctCtrl.getList';
 
// inside the class
@wire(getList) accounts;
<template lwc:if={accounts.data}>
  ...
</template>
  • A wired property has .data and .error.
  • cacheable=true is required for @wire, and such a method must not change data.
8

Automation and security

What runs without code, and who can see what.

Which tool

Need Use
Stop bad data being saved Validation rule
A value worked out from other fields Formula field
A total of child records Roll-up summary field
Update records, send email, guide a user Flow
Complex logic or very large volumes Apex trigger
  • Try clicks before code.
  • Flow is the tool for new automation. Workflow Rules and Process Builder are the older ones it replaces.

Order of a save

A simplified version of what happens when a record is saved:

  1. Required fields and field formats are checked.
  2. Before-save flows run.
  3. before triggers run.
  4. Validation rules run.
  5. The record is saved, but not yet committed.
  6. after triggers run.
  7. After-save flows and other automation run.
  8. Roll-up summaries on the parent are updated.
  9. Everything is committed.

An error at any step undoes the lot.

Access layers

Layer Controls Set with
Object Create, read, edit, delete Profiles, permission sets
Field Seeing or editing one field Field-level security
Record Which records Sharing settings

Record access, from widest to narrowest control:

  1. Org-wide defaults: the baseline for everyone.
  2. Role hierarchy: managers see what their team sees.
  3. Sharing rules: open records to groups.
  4. Manual sharing: one record, one person.

Give access with permission sets. Keep profiles minimal.

Formulas

IF(Amount > 1000, "Big", "Small")
ISBLANK(Phone)
ISPICKVAL(StageName, "Closed Won")
TEXT(StageName)
TODAY() - DATEVALUE(CreatedDate)
Account.Name & " - " & Name
  • Formulas use double quotes and & to join text.
  • ISPICKVAL or TEXT is needed to compare a picklist.
9

Salesforce CLI

The sf command for working with orgs from a terminal.

Connect

sf org login web --alias dev
sf org list
sf org open --target-org dev
sf org display --target-org dev
  • --alias gives the org a short name to use in other commands.
  • Add --set-default to skip --target-org afterwards.

Create

sf template generate project \
  --name my-app
sf template generate apex class \
  --name AccountService
sf template generate lightning component \
  --name helloWorld --type lwc
  • Without --type lwc the component is an Aura one.

Deploy and retrieve

sf project deploy start --target-org dev
sf project deploy start --dry-run
sf project retrieve start \
  --metadata ApexClass
sf project retrieve start \
  --manifest package.xml
  • --dry-run checks the deploy and runs tests without saving anything.

Test and query

sf apex run test --code-coverage
sf apex run test \
  --class-names AccountServiceTest
sf apex run --file script.apex
sf data query \
  --query "SELECT Id, Name FROM Account"

Scratch orgs

sf org create scratch \
  --definition-file \
  config/project-scratch-def.json \
  --alias feature --duration-days 7
sf org delete scratch --target-org feature
  • A scratch org is a temporary, empty org for building one feature.
10

More help

The official pages to check details against.