Here is apex trigger for creating contact when new account record is get added.
trigger AccountTrigger2 on Account(after insert) {
if (trigger.isInsert && trigger.isAfter) {
List < Contact > lstContact = new List < Contact > ();
for (Account acc: trigger.new) {
Contact con = new Contact();
con.FirstName = 'Test Contact' + acc.Name;
con.LastName = 'Test';
con.AccountId = acc.Id;
lstContact.add(con);
}
if (!lstContact.isEmpty()) {
database.insert(lstContact);
}
}
}
Scenario
Every time a new Account is created, you may want a Contact to be created automatically and linked to it. This trigger does exactly that.
How the code works
after insert is used because the Account needs an Id before a Contact can point to it through AccountId.
Trigger.new holds all the Accounts that were just inserted.
The loop builds one Contact per Account and adds it to a list.
A single database.insert(lstContact) call saves all Contacts at once, outside the loop. This keeps the code safe for bulk inserts and within Salesforce governor limits.
Points to note
LastName is required on Contact, which is why it is set to Test.
The trigger.isInsert && trigger.isAfter check is optional here, because the trigger is already declared as after insert. It becomes useful when you add more events to the same trigger.
In real projects, avoid hardcoded test values. Use meaningful data, for example con.LastName = acc.Name;.
How to test
Create a new Account.
Open its Related tab and confirm the Contact appears.
Import several Accounts at once and confirm each gets its own Contact.
FAQ
Why not use a before insert trigger? The Account does not have an Id yet, so the Contact cannot be linked.
Why one insert outside the loop? DML inside a loop can hit the 150 DML statement limit in a bulk operation.
Can Flow do this instead? Yes. A record-triggered Flow can also create the Contact. Triggers give more control for complex logic.