2

The basic question is if it's possible to create an INSERT operation using a SELECT statement as the source, rather than selecting individual records, pulling them out of the Salesforce database into a large buffer array and then performing an insert() on each one to push it back into the Salesforce database. It might look something like this:

INSERT INTO ClassEnrollment (StudentName, ClassName) SELECT StudentName, 'GYM' FROM Students WHERE FitnessScore >= 10

The reason I'm looking for this kind of bulk insert statement is to avoid governer limits if there are tens of thousands of records. In other databases a bulk insert statement like this is vastly more efficient than trying to insert thousands of records individually.

As a bonus is there a way to do this dynamically, like database.query(), so that the statement can be constructed at runtime instead of being fixed?

  • 1
    Apex Batch is something that might allow you to achieve this, avoiding governor limits – kurunve Aug 16 at 20:09
  • 1
    You can at max insert 10000 rows in a table(Given the Trigger or process builder does not timeout). You have to stick with Batch Apex – Pranay Jaiswal Aug 16 at 21:49
7

SOQL is a read only language. You cannot in any way use SOQL to perform write operations.

4

As @Adrian said, SOQL is read only. However, Salesforce provides you with a way to do this when you have many records and you have Gov Limit concerns.

It is called Batch Apex. You would create a class, define a query (which can be dynamic) and then iterate through the record. You can also, optionally, specify how big the batch is (ie: how many records get processed in one go). You can try to put that batch as big as you can, while staying under gov limits.

You can play with the constructor to get fancy with your queries (ie: pass some parameter to change the query being used).

Batchable classes follow this general format:

public class MyBatchableClass implements Database.Batchable<sObject>{
   global Database.QueryLocator start(Database.BatchableContext BC){
      String query = 'query the records you want here'; 

      return Database.getQueryLocator(query);
   }

   global void execute(Database.BatchableContext BC, List<sObject> scope){
      //Build a list of the new object based on the items included in the scope variable
      //insert the list of the new object
    }

   global void finish(Database.BatchableContext BC){
      //Cleanup goes here
   }
}

Full documentation is here

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.