Okay, one last thing about insert.
You can only issue the insert DML operation if the sObject records do not already have a Salesforce Id associated with them. Here are a couple of scenarios to keep in mind:
Account firstAccount = [Select Id, Name FROM Account ORDER BY CreatedDate DESC LIMIT 1]; insert firstAccount;
You'll get back a DML Exception: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]
. The error can't get any clearer than that. firstAccount
already had an Id, because it already existed in the database, so we can't pass it as an argument to an insert statement.
But remember, the system only knows there is an Id
because it's referenced in the firstAccount
variable. Technically, you could do this to insert the account record.
Account latestAccount = [Select Id, Name FROM Account ORDER BY CreatedDate DESC LIMIT 1]; latestAccount.Id = null; // clear out the Id insert latestAccount; // now you have a duplicate account with a different Id
Do with that information, what you will.