-3

I have a simple trigger on account object. In which i am querying the account records. When I am trying to insert 5000 account records in bulk the

System.LimitException: Too many query rows: 50001

is being thrown at line 3 i.e List<Account> accountList = [select id,BillingState from account]; can anyone help me with the solution?

trigger AccountTrigger on Account (after insert) {
    if (Trigger.isAfter) {
        List<Account> accountList = [select id,BillingState from account];
    }
}
1

2 Answers 2

3

Since the exact use case is not known, the more appropriate solution will be to include a where clause such that it brings the required records which shall not be greater than 50000. At present, it will bring all the records in the list from the object which may be more than 50K.

2
  • currently do not have any account records in my org. I am just trying to insert 5000 records in bulk and also I cannot use the ''WHERE" clause as I need to fetch all the account records. I know we can handle such logic in Batch is there any way that we can do in the apex trigger?
    – Niharika B
    Jun 10, 2022 at 11:21
  • put a limit at the end of the query to 49800. The remaining 200 records shall be part of Trigger.new assuming batch size of insert is 200. Jun 10, 2022 at 12:54
3

That query is retrieving every Account record in your org. I do not know what your ultimate aim is here - perhaps you are learning and just trying different things - but you need a WHERE clause to retrieve a specific subset of records. Something like

...WHERE Id IN :Trigger.New

Again, the specifics of the WHERE clause are dependent on what you are trying to achieve.

1
  • I currently do not have any account records in my org. I am just trying to insert 5000 records in bulk and also I cannot use the ''WHERE" clause as I need to fetch all the account records. I know we can handle such logic in Batch is there any way that we can do in the apex trigger?
    – Niharika B
    Jun 10, 2022 at 11:26

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