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
Vigneshwaran LoganathanVigneshwaran Loganathan 

Need Query for the below situation

Hi all,

I got a question in interview like.. you have a list with 100 records how will you get records from 25 to 75 from that list?

Somehow I have wrote a code like,
 
trigger GetRecs on Opportunity (before insert,before update) 
{
  list<Opportunity> opps = new list<Opportunity>();
  list<Opportunity> opx = new list<Opportunity>();  
    opps=[select id,name from Opportunity where name!=null ORDER BY Name ASC LIMIT 100];
    //opx=[select id,name from Opportunity where ]
    map<integer,opportunity> mapx=new map<integer,opportunity>();
    for(integer i=0;i<101;i++)
    {
      mapx.put(i,opps[i]);
    }
    
    for(integer i=25; i<=76;i++)
    {
      if(mapx.containsKey (i)==true)
      {
        list<Opportunity> os=new list<Opportunity>();
        os.add(mapx.get(i));
        system.debug('recs'+opps[i]);
      }
    }
}
What is the mistake here?

Thanks
 
Ray KaushikRay Kaushik
As the record count is less than 2000 you can always use offset query. Details - https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select_offset.htm 


Query sample will be something line this 
 
SELECT fieldList
FROM objectType
[WHERE conditionExpression] 
ORDER BY fieldOrderByList
LIMIT numberOfRowsToReturn
OFFSET numberOfRowsToSkip

Do let me know if that answers your question.


Thanks,

Ray
Vikash GoyalVikash Goyal
For this you have to use OFFSET in SOQL. 

For details you can visit the following link :
https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select_offset.htm

For your case SOQL will be like this :
 
[SELECT Id, Name FROM Opportunity 
 WHERE Name != null 
ORDER BY Name ASC 
LIMIT 50
OFFSET 24]
Please mark this as answer if it solved your problem.

Thanks
Vikash Goyal