function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Patrick ConnerPatrick Conner 

Bulkify Code to Create Accounts on Contact Upserts

I'm trying to bulkify the following code, which works well for a single contact and parent account creation:
trigger createacc on Contact (after insert) {
list<Contact > con=[select id,lastname,email from contact where id in:Trigger.newMap.keySet()];
list<account >acc =new list<account>();
list<contact>cc1 =new list<contact>();
for(contact c : con)
account a =new account ();;;
insert acc;
for(account a1:acc){
system.debug('---------------------this is id --------------------';
for(contact c : con){;
update cc1;

Any help would be greatly appreciated! Thank you!
Best Answer chosen by Patrick Conner
Abhishek BansalAbhishek Bansal
Hi Patrick,

I would suggest you to create two triggers for this requirement.
First trigger will simply insert the account records when contacts are inserted :
trigger createacc on Contact (after insert) {
	List<Account> accList = new List<Account>();
	for(Contact con :{
		Account acc = new Account();;;
	if(accList.size() > 0){
		insert accList;

Now second trigger will be written on Account which will update all the related contacts with account id :
trigger updateContact on Account (after insert){
	Set<String> setOfEmails = new Set<String>();
	for(Account acc :{
		if(acc.Email__c != null){
	Map<String,Contact> mapOfContacts = new Map<String,Contact>();
	for(Contact con : [Select AccountId,Email from Contact where Email IN :setOfEmails]){
	List<Contact> conToUpdateList = new List<Contact>();
	for(Account acc :{
			mapOfContacts.get(acc.Email__c).AccountId =;
	if(conToUpdateList.size() > 0){
		update conToUpdateList;

Please use both triggers for this requirement.
Let me know if you need more information on this.

Abhishek bansal