In Apex, the insert statement is used for performing data insertion operations, specifically for adding new
records to the Salesforce database. You can use the insert statement to insert records for both standard and
custom objects.
Here's a basic example of how to use the insert statement to insert a new Account record:
Account newAccount = new Account(Name='New Account Name');
insert newAccount;
We create a new Account object named newAccount.
We set the Name field of the newAccount object to the desired account name.
We use the insert statement to insert the newAccount object into the Salesforce database. Once inserted, it will be assigned a unique Salesforce ID.
List<Account> accountList = new List<Account>();
// Create multiple Account records and add them to the list
accountList.add(new Account(Name='Account 1'));
accountList.add(new Account(Name='Account 2'));
accountList.add(new Account(Name='Account 3'));
// Insert all the records in the list
insert accountList;
In this example, we create a list of Account objects, populate the list with multiple records, and then use the insert statement to insert all the records in the list.
It's important to note that the insert statement may encounter validation rules, triggers, or other operations that can
lead to exceptions or errors. Proper error handling should be implemented to deal with potential issues when performing
data insertion operations in your Apex code.