-5

For Example:

 for(Contact con : [Select Id,Salary__c From Contact Where AccountId = :accId Limit 100]){
            System.debug('Check min'+con.Salary__c);
 }

How to loop though the results and retrieve the minimum salary without changing my SOQL query?

2 Answers 2

1

Since you're just looking to compare it on the loop, you can use this:

Contact minSalCon;
Decimal minSal;
for(Contact con : [Select Id,Salary__c From Contact Where AccountId = :accId Limit 100]){
    System.debug('Check min'+con.Salary__c);
    if(minSal == null || con.Salary__c < minSal){
        minSal = con.Salary__c;
        minSalCon = con; //in case you need to do some logic on the contact
    }
}
1
  • Thanx! That is what I was looking.
    – avidForce
    Commented Aug 16, 2016 at 14:48
1

Try with the below query:

for(AggregateResult agr : [Select AccountId accId, MIN(Salary__c) minSal From                
                           Contact Where AccountId =: accId Limit 100 group by AccountId]){
      System.debug('Check min'+agr .get('minSal'));
 }

You can use this query for multiple Accounts as well

5
  • I want custom functionality for ex using for loop, I already Used AggregateResult and its working fine.
    – avidForce
    Commented Aug 16, 2016 at 12:07
  • The LIMIT clause does not work well in aggregate queries.
    – Adrian Larson
    Commented Aug 16, 2016 at 12:08
  • 1
    This answer would be better if you explained what the query actually does (ie. uses an Aggregate Function).
    – Derek F
    Commented Aug 16, 2016 at 12:08
  • 2
    @avidForce Can you explain why you're not looking for a query that uses Aggregate Functions? Using MIN() is about as efficient as it gets. If you have something that's already working, why are you looking to rewrite it using code that is more complex?
    – Derek F
    Commented Aug 16, 2016 at 12:11
  • @Darek F Just want to create and see my own logic, I know using AggregateResult is more efficient.
    – avidForce
    Commented Aug 16, 2016 at 12:13

Not the answer you're looking for? Browse other questions tagged .