October 28, 2014

How to query Field History Tracking records in Salesforce?

If field history tracking is enabled for an object, the changes are stored in history table for that particular object.

The API name of these tables follows a simple convention so should be easy to find. For standard objects, the name of the history table follows the format: 'ObjectNameHistory' so for the Account object the history table is AccountHistory.

For custom objects, the name of the convention simply replaces the 'c' on the end of the API name with 'History'. So, for a custom object call My_Custom_Object__c the history table is called My_Custom_Object__History.

Sample Queries:

SELECT AccountId, OldValue, NewValue, IsDeleted, Id, Field, CreatedBy.Name From AccountHistory WHERE AccountId=:accountId ORDER BY CreatedDate DESC

SELECT Id, Name, (Select OldValue, NewValue From My_Custom_Object__History) FROM My_Custom_Object__c

Cheers!!!

8 comments:

  1. Can u please explain js in lwc it will be very helpful

    ReplyDelete
    Replies
    1. JS in LWC runs on client side(browser). It can call apex methods and render it on the screen.
      https://www.infallibletechie.com/search/label/LWC

      Delete
    2. if we using Apex class to fetch the data meant how to cover it in test class? Because test data changes are not stored in Field History

      Delete
    3. Currently not supported. Vote for this idea - https://success.salesforce.com/ideaView?id=08730000000h6RwAAI

      Delete
    4. Thanks for you response

      Delete
  2. Regarding test classes that fetch History, just fetch some real data. You could hard-code based on some history data that exists in the org, but better, read a field like "Date Closed" on Opportunity and then use your class to fetch that change to StageName from history (assuming that field is tracked).

    ReplyDelete
    Replies
    1. Agreed. Using seeAllData=true is not an ideal solution.
      Instead, you can store the history records in Static Resource and fetch it using Test.loadData() in Test Class.

      Delete