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
Rakesh ERakesh E 

How to get MIN and MAX values of a field in a custom object .

We have a custom object which holds about 2 lakh records.

 

when i try to get MIN and MAX values of a custom field iam getting limit exception.

 

System.LimitException: Too many query rows: 50001 

 

can anyone please explain why iam getting these error even though iam not selecting all records.

 

And how an i get this values.below is the query.

 

List<AggregateResult> result =[select  min(id__c),max(id__c) from customobjectname];

 

 

 

thanks in advance

Best Answer chosen by Admin (Salesforce Developers) 
Rakesh ERakesh E

thank you navatar 

 

i tried the query u posted , but got some error and changed it as following and it is working

 

 customobjectname result =[select  id__c from customobjectname  order by id__c desc limit 1];

 

 id__c is auto number here.

 

 

 


All Answers

Navatar_DbSupNavatar_DbSup

Hi,

 

You are making the SOQL query on that object. You have to make the limit 50000 inside the SOQL. You can use the order by inside the SOQL to get the desired result.

 

Try the below as reference:

 

List<AggregateResult> result =[select  min(id__c),max(id__c) from customobjectname order by createddate desc limit 50000];

 

Did this answer your question? If not, let me know what didn't work, or if so, please mark it solved. 

SRKSRK

I belive if u put limit it wont cover all u r record

SRKSRK

What is this Id__c field
the values is insert by user or it auto generate

also if the id__c values of the record which is created recently is maxminum then u can just order by createddate & limit 1

u u can create a custom setting & create a trigger so  when ever u record is insert or update & the valus in custom seeting is less thn the value in record u update the custom seeting eith the record's value so in this way u can mention the max & min value for that object in custom seeting

Rakesh ERakesh E

thank you navatar 

 

i tried the query u posted , but got some error and changed it as following and it is working

 

 customobjectname result =[select  id__c from customobjectname  order by id__c desc limit 1];

 

 id__c is auto number here.

 

 

 


This was selected as the best answer
Ken Koellner @ EngagewareKen Koellner @ Engageware
I suspect it would be faster to run two queries, order by the field ASC in one and DESC in the other and LIMIT 1 on both.