A Guide to Retrieving Historical Records in Salesforce Using SOQL

Varshit YadavVarshit Yadav
2 min read

For querying history records using soql we first need to enable history tracking

🔹 Step 1: Go to Object Manager

  1. Click the gear icon (⚙️) → Setup.

  2. In the Quick Find box, type "Object Manager" and click it.

  3. Select the object you want to track (e.g., Account, CustomObject__c).

🔹 Step 2: Enable History Tracking for the Object

  1. Inside the object page, click "Fields & Relationships".

  2. In the top-right, click "Set History Tracking".

    • If you don’t see this option, make sure the object supports tracking (some system objects don’t).

🔹 Step 3: Choose the Fields to Track

  1. Check "Enable Field History Tracking".

  2. Select up to 20 fields you want to track.

  3. Click Save.

When you enable Field History Tracking on a custom object in Salesforce, Salesforce automatically creates a special history object to store all the changes made to the tracked fields.

For example, if your custom object’s API name is Sport__c, the history tracking records are stored in a related object called Sport__History.

if your object is standard then you have to use StandardObjectApiNameHistory, for example

history object for Account will be AccountHistory

Once done, You can query your history

*Important Note on Testing Field History Tracking

You cannot insert or create history records directly from Apex classes or test classes because Salesforce manages history records automatically. This means:

  • You cannot write code that explicitly inserts records into the Sport__History (or any __History) object.

  • When writing test classes, code that queries history objects may not get full coverage because test data doesn’t generate history records by default.

  • This limitation can make it tricky to cover Apex logic that depends on history records during tests.

0
Subscribe to my newsletter

Read articles from Varshit Yadav directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Varshit Yadav
Varshit Yadav