I have a VF page that allows a user to perform dynamic searching in filter on an object.

The user can easily specify a query that will result in more than 50,000 records. I would like to catch this error and prompt the user to narrow their search but unfortunately Salesforce doesn't let you catch Limit Exceptions.

Are their any good solutions for this? I suppose I could make the call with a remote function and error handle with JS, but my querying class is very object oriented so rebuilding everything for a static method is not really ideal.


In the SOQL set a LIMIT of say 1,000 records (or whatever you feel your users would want as a maximum set of results) and check the size of the returned results. If that size is 1,000 (implying there may be many more results) then tell the user to narrow their search.


Whilst there is no way of catching Salesforce limits Exception, you can use the Limits class to avoid hitting them and throw your own Exceptions. For your question of avoiding 50,000 rows retrieved you can use a database.countQuery to check the amount of records on the row, (see below). You will need to know the following however This will count against your SOQL limit (This might change in the future).

Integer count = database.countQuery('select count() from Sobject');
If (count > 50,000)
       Throw new Execption('You have lots of records - ' + count + ' records');
  • 1
    Tim, while code alone answers can solve the problem, it will be more useful if we explain the approach & how the code snippet helps to resolve the issue. – Vamsi Krishna Gosu Nov 2 '15 at 11:31
  • 1
    Count query will also fail if it returns count > 50000 rows. So this will not work. You rather need to use LIMIT as Keith C suggested – neff Nov 2 '15 at 12:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.