How to Get Id of Inserted Record via Apex

  • How can I get the Id of a record which has been inserted using Apex?

    Can you please elaborate your question? If you are using statement like "insert account", the Id of the account can be accessed by "account.Id".

    better if you can share your code

    If by chance you are using triggers and are wondering where the id is on a `before insert` trigger, it is not available as the record is not yet saved. You will only be able to access the id on an insert event within the `after insert` trigger.

    This question has been re-asked multiple times. If there's an FAQ, this deserves to be on it.

  • The platform allocates an ID value and sets it in an SObject's ID field implicitly as part of the insert operation:

    Account a  = new Account(Name = 'Acme');
    // a.Id is null here
    insert a;
    // a.Id now has a value set by the platform

    Fields are accessed using just a dot and the field name; there isn't a corresponding getId() method. (The generic field get method does work for 'Id'.)

    So most of the time you do not assign a value to an object's ID field. An exception is where you have the ID of the object (perhaps from a lookup field on a different object) and want to update the object. In that case you can assign the ID and so save having to first query the object:

    Account a = new Account(Id = accountId, Name = 'New Name');
    update a;
  • If you are using statement like "insert account;", the Id of the account can be accessed by "account.Id;". Below code will give you an overview.

    Account acct = new Account(Name='SFDC Account');
    insert acct;
    system.debug("Inserted Account Id = "+acct.Id);

    acct.Id will provide the Id for the Account record acct.The debug statement above will write the Id to the Debug logs.

    Please visit the below link for DML usage and using Id for subsequent logic(s) :

  • Account acct = new Account();
    acct.put('Name', 'Test');
    Id AccountId;
    Database.SaveResult[] srList = Database.insert(acct);
    for (Database.SaveResult sr : srList)
        AccountId = sr.getId();

    welcome to the SF community. it is always good to elaborate your code with some explanation while adding as answer.

License under CC-BY-SA with attribution

Content dated before 7/24/2021 11:53 AM

Tags used