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
Michael MMichael M 

How to query the record that was created right before and right after the current record?

Hello, I have a task to create "previous" and "next" buttons on detail page layout. I know that in my apex controller I will need to be able to write a SOQL query to fetch the record where the createddate was directly before the current record's createddate, and the record where the createddate was directly after the current record's createddate. I'm not sure if this is a basic question or not, but how can such a query be done? Thank you.
Best Answer chosen by Michael M
Vishwajeet kumarVishwajeet kumar
Hello,
If you wana do it though SOQL it will require two queries.
Example for account - currentAccount: 

Before record - use where clause as createdDate < :currentAccount.createdDate : select id,Name,createdDate from Account where createdDate < :v_Acc.createdDate order by createdDate ASC LIMIT 1

After record - use where clause as createdDate > :currentAccount.createdDate : select id,Name,createdDate from Account where createdDate > :v_Acc.createdDate order by createdDate ASC LIMIT 1

Not sure what application context is look into ListControllers too, it provides pagination capablities.

Thanks

All Answers

Vishwajeet kumarVishwajeet kumar
Hello,
If you wana do it though SOQL it will require two queries.
Example for account - currentAccount: 

Before record - use where clause as createdDate < :currentAccount.createdDate : select id,Name,createdDate from Account where createdDate < :v_Acc.createdDate order by createdDate ASC LIMIT 1

After record - use where clause as createdDate > :currentAccount.createdDate : select id,Name,createdDate from Account where createdDate > :v_Acc.createdDate order by createdDate ASC LIMIT 1

Not sure what application context is look into ListControllers too, it provides pagination capablities.

Thanks
This was selected as the best answer
Michael MMichael M
Thank you very much. Out of curiousity, is there any other way besides Soql that you would recommend?