function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Arek Stegienko DevArek Stegienko Dev 

What's the best way to query Lead History objects

I need to get a list of lead history objects between two dates.  I've come up with this approach:

 

[SELECT (SELECT LeadId, CreatedDate, Field, OldValue, NewValue FROM Histories WHERE CreatedDate >= :fromDate AND CreatedDate <= :toDate) FROM Lead]

 

however, that returns a list of all leads that I then would have to go through and check if they actually contain any history.  Is there a way to directly access the lead history object and query that table?

 

Thanks,

Harry

asish1989asish1989

Hi

   Try this..

      
[SELECT (SELECT LeadId, CreatedDate, Field, OldValue, NewValue FROM LeadHistories WHERE CreatedDate >= :fromDate AND CreatedDate <= :toDate) FROM Lead]

 

 

Did this post solve your problem If so please mark it solved so that others benifited.

 

Thanks

asish

Teach_me_howTeach_me_how

can i create trigger on leadHistory object?

asish1989asish1989

Hi

  I think we cant create Trigger on LeadHistory Object .

  Generally We can create Trigger on a object on which we  can be able to insert, update , delete record  so that Trigger can be fired.

 

 

 

Thanks

asish

Richard Fiekowsky 3Richard Fiekowsky 3
The sObject is "LeadHistory" . While many tools won't support queries against it, you can query with the "Workbench" and get the results via the "Bulk CSV" option. Some of the fields of LeadHistory do not support filtering, so you might need to filter it yourself in Excel. There's no need to use a subselect as in "SELECT (SELECT fields FROM LeadHistory) FROM Lead" . Just "SELECT fields FROM LeadHistory" will do, and is less likely to throw errors. But if you do want to filter on data that is in the Lead itself, such as getting recent changes to Leads with certain Lead Statuses, the query with the subquery would be like
SELECT fields FROM LeadHistory WHERE LeadId IN ( SELECT Id FROM Lead WHERE Status IN ("Known", "Inquiry") ) AND CreatedDate >= THIS_YEAR
The changes are recent in this example, it does not matter when the Lead was created. Of course "fields" means whichever fields you want from the LeadHistory records. LeadId is the field of LeadHistory that points to the Lead, it isn't the Id of the LeadHistory record. 
For the original question, in Apex code, the query to get all changes between two dates inclusive would be 
List<LeadHistory> myHist = [SELECT LeadId, CreatedDate, Field, OldValue, NewValue FROM LeadHistory WHERE CreatedDate >= :fromDate AND CreatedDate <= :toDate] ;