Which of the two approaches to get max value from all records of object is correct?
It sounds like you have already found the answer: using LIMIT 1
will avoid hitting LimitException
. Take a look at this post, however. You may notice better performance if you change your query to:
List<Resource__c> mpList = [
SELECT Price__c FROM Resource__c
ORDER BY Price__c DESC NULLS LAST
LIMIT 1
]
Take a look at Working with Very Large SOQL Queries. Querying for field != null
will hurt your performance.
Typically, a custom index isn’t used in these cases.
- The queried values exceed the system-defined threshold.
- The filter operator is a negative operator such as NOT EQUAL TO (or !=), NOT CONTAINS, and NOT STARTS WITH.
- The CONTAINS operator is used in the filter, and the number of rows to be scanned exceeds 333,333. The CONTAINS operator requires a full scan of the index. This threshold is subject to change.
- You’re comparing with an empty value (Name != '').