External Id plays very important role if you want to update records without knowing the record Ids or want to relate the child record with parent record without knowing the parent record Id.
As a best practice, you should always make External Id unique. If you are performing upsert with External Id, then following situations will occur:
I am going to cover 2 different aspect of using external Id in apex.
SOQL INJECTION IN SOQL
CUSTOM METADATA AND CUSTOM SETTINGS IMPLEMENTATION TRICKS
SMART TABLE USING ANGULARJS IN VISUALFORCE PAGE
REST API TUTORIAL FOR SALESFORCE
VISUALFORCE COMPONENT FOR RECORD STATUS BAR
FETCHING FILE FROM EXTERNAL/PUBLIC URL AND STORING IT IN SALESFORCE
As a best practice, you should always make External Id unique. If you are performing upsert with External Id, then following situations will occur:
- If no record is found in table with provided External Id, then it will create record in table.
- If 1 record is found in table with provided External Id, then it will update record in table.
- If more than 1 records is found in table with provided External Id, then system will throw an error.
I am going to cover 2 different aspect of using external Id in apex.
- Updating a record with External Id
Create a External Id field on Account as Account_Unique_Number__c and mark it as External Id and unique while creating it.Now we will create a new record using upsert.
Execute below command in developer console
List<Account> acclist=new list<Account>();
acc.name='Demo test1';
acc.Account_Unique_Number__c='00001';
acclist.add(acc);
Schema.SObjectField ftoken = Account.Fields.Account_Unique_Number__c;
Database.UpsertResult[] srList = Database.upsert(acclist,ftoken,false);
for (Database.UpsertResult sr : srList) {
if (sr.isSuccess()) {
// Operation was successful
}
else {
// Operation failed, so get all errors
for(Database.Error err : sr.getErrors()) {
System.debug('error has occurred.' + err.getStatusCode() + ': ' + err.getMessage());
System.debug('fields that affected this error: ' + err.getFields());
}
}
}
As there is no record in Account with Account_Unique_Number__c as 00001, system will create a new record.
Now again we will run same script in developer console and will specify some more field values:
List<Account> acclist=new list<Account>();
Account acc=new Account();
acc.name='Demo test1';
acc.Account_Unique_Number__c='00001';
acc.type='Other';
acc.Industry='Banking';
acclist.add(acc);
Schema.SObjectField ftoken = Account.Fields.Account_Unique_Number__c;
Database.UpsertResult[] srList = Database.upsert(acclist,ftoken,false);
for (Database.UpsertResult sr : srList) {
if (sr.isSuccess()) {
// Operation was successful
}
else {
// Operation failed, so get all errors
for(Database.Error err : sr.getErrors()) {
System.debug('error has occurred.' + err.getStatusCode() + ': ' + err.getMessage());
System.debug('fields that affected this error: ' + err.getFields());
}
}
}
Now you will see that system will update the record as it was able to find a Account record with Account_Unique_Number__c as 00001
- Relating a child record with parent record by using parent record Id
In order to understand this, we will create contact record and will relate to account using Account_Unique_Number__c. Execute below code in developer console:
List<Contact> conlist=new list<Contact>();
Contact con=new Contact();
con.lastname='Kumar';
con.Firstname='Kumar';
con.email='sunil02kumar@gmail.com';
Account acc=new Account(Account_Unique_Number__c='00001');
con.Account=acc;
conlist.add(con);
Database.UpsertResult[] srList = Database.upsert(conlist,false);
for (Database.UpsertResult sr : srList) {
if (sr.isSuccess()) {
// Operation was successful
}
else {
// Operation failed, so get all errors
for(Database.Error err : sr.getErrors()) {
System.debug('error has occurred.' + err.getStatusCode() + ': ' + err.getMessage());
System.debug('fields that affected this error: ' + err.getFields());
}
}
}
This will create a new contact for Account which have Account_Unique_Number__c as 00001.
In above code snippet, you can see that in order to relate contact with account, we are not specifying the account 15 or 18 digit record id. We are just specifying the external Id of account and system will maintain the relationship.
If you refer custom object as parent object then refer it with __r. For example in above scenario, if i have to relate contact with custom object say Parent_Obj__c, then I will use below code:
If you refer custom object as parent object then refer it with __r. For example in above scenario, if i have to relate contact with custom object say Parent_Obj__c, then I will use below code:
Parent_Obj__c obj = new Parent_Obj__c(Unique_Number__c='00001');
con.Parent_Obj__r = obj;
Why it is recommended to mark External Id as unique?
Imagine you are creating a contact and specified External Id of parent. Suppose there are 2 records in account table with same value, then system will not able to identify with whom it needs to relate the contact and will throw error saying more than 1 match found.
Same is applicable when you update the record with External Id.
Same is applicable when you update the record with External Id.
More Blogs>>:
DYNAMIC APEX IN SALESFORCE
SOQL INJECTION IN SOQL
CUSTOM METADATA AND CUSTOM SETTINGS IMPLEMENTATION TRICKS
SMART TABLE USING ANGULARJS IN VISUALFORCE PAGE
REST API TUTORIAL FOR SALESFORCE
VISUALFORCE COMPONENT FOR RECORD STATUS BAR
FETCHING FILE FROM EXTERNAL/PUBLIC URL AND STORING IT IN SALESFORCE
Some phone systems distribute the database across multiple servers. ShoreTel, for example, distributes components of the database to application servers and distributed voice mail servers that characterize the single image architecture in a multi-site environment. mysql dashboards
ReplyDeleteIn the context of databases, particularly in the Salesforce ecosystem, the term "upsert" refers to an operation that either updates an existing record or inserts a new record if it doesn't already exist. This is typically done based on a specified external ID field, which uniquely identifies records across systems. Here’s how you can use Database.upsert with an external ID field in Salesforce Apex:
DeleteCloud Computing Projects Final Year Projects
Big Data Projects For Final Year Students
Example Scenario
Let's say you have a custom object CustomObject__c in Salesforce with an external ID field named External_Id__c. You want to upsert records into this object based on the External_Id__c field.
I like the blog format as you create user engagement in the complete article. Thanks for the informative posts.
ReplyDeleteSelenium Training in Chennai
Selenium Course in Chennai
iOS Training
iOS Course in Chennai
Digital Marketing Course in Chennai
Digital Marketing Training in Chennai
I am getting the error as VARIABLE_ASSIGNMENT [7]|ftoken|"common.apex.runtime.impl.ApexFieldToken@3db6c477"|0x3db6c477 when updating a record with external id.Could you please guide me how to resolve this?
ReplyDeleteGreat blog thanks for sharing Looking for the best creative agency to fuel new brand ideas? Adhuntt Media is not just a digital marketing company in chennai. We specialize in revamping your brand identity to drive in best traffic that converts. Buckle up for a ride that is going to be filled with SEO, Social media marketing, unique Graphic & Logo design and efficient ads strike the perfect chord! Join the Adhuntt Media adventure right at Adhuntt Media.
ReplyDeletedigital marketing company in chennai
seo service in chennai
web designing company in chennai
social media marketing company in chennai
Nice information, valuable and excellent design, as share good stuff with good ideas and concepts, lots of great information and inspiration, both of which I need, thanks to offer such a helpful information here.
ReplyDeletedigital marketing course in chennai
SKARTEC Digital Marketing
best digital marketing training in chennai
seo training in chennai
online digital marketing training
best marketing books
best marketing books for beginners
best marketing books for entrepreneurs
best marketing books in india
digital marketing course fees
best seo service in chennai
SKARTEC SEO Services
digital marketing resources
digital marketing blog
digital marketing expert
Nice post. Thanks for sharing! I want people to know just how good this information is in your article. It’s interesting content and Great work.
ReplyDeletehttps://360digitmg.com/digital-marketing-training-in-hyderabad
Web and Pro Infomedia is Best Digital Marketing Company in Lucknow
ReplyDeleteThis is a wonderful article, Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck.
ReplyDeleteData Science Institute in Bangalore
I will really appreciate the writer's choice for choosing this excellent article appropriate to my matter.Here is deep description about the article matter which helped me more.
ReplyDeletedata science course in guntur
Thanks for posting useful information.You have provided an nice article, Thank you very much for this one.
ReplyDeleteacte chennai
acte complaints
acte reviews
acte trainer complaints
acte trainer reviews
acte velachery reviews complaints
acte tambaram reviews complaints
acte anna nagar reviews complaints
acte porur reviews complaints
acte omr reviews complaints
This is really good post here. Thanks for such valuable information. Quality content is what always gets the visitors coming.
ReplyDeleteIELTS Coaching in chennai
German Classes in Chennai
GRE Coaching Classes in Chennai
TOEFL Coaching in Chennai
spoken english classes in chennai | Communication training
Brilliant work and I really liked the blogging style and content in this, keep it up and also check this out
ReplyDeleteFull Stack Course Chennai
Full Stack Training in Bangalore
Full Stack Course in Bangalore
Full Stack Training in Hyderabad
Full Stack Course in Hyderabad
Full Stack Training
Full Stack Course
Full Stack Online Training
Full Stack Online Course
I simply want to mention I am just all new to blogging and site-building and truly loved you’re web page. Almost certainly I’m planning to bookmark your site . You really have outstanding stories. Many thanks for revealing your webpage.…
ReplyDeleteAzure Training in Chennai
Azure Training in Bangalore
Azure Training in Hyderabad
Azure Training in Pune
Azure Training | microsoft azure certification | Azure Online Training Course
Azure Online Training
Great Article. Thank you for sharing! Really an awesome post for every one.
ReplyDeleteSalesforce Training in Chennai
Salesforce Online Training in Chennai
Salesforce Training in Bangalore
Salesforce Training in Hyderabad
Salesforce training in ameerpet
Salesforce Training in Pune
Salesforce Online Training
Salesforce Training
I like the blog format as you create user engagement in the complete article. Thanks for the informative posts.Digital Marketing Training in Chennai
ReplyDeleteDigital Marketing Training in Velachery
Digital Marketing Training in Tambaram
Digital Marketing Training in Porur
Digital Marketing Training in Omr
Digital Marketing Training in Annanagar
Wow, What a Excellent post. I really found this to much informatics. It is what i was searching for.I would like to suggest you that please keep sharing such type of info.Thanks Bethlehem Website Development
ReplyDeleteThanks for the awesome post.
ReplyDeleteBest Web designing company in Hyderabad
Best Web development company in Hyderabad
thanks for sharing this information
ReplyDeletefull stack developer course
full stack developer course in bangalore
Do you Need Instant Loan from $2,000 to $50,000,000.00 with no collateral required and receive a no obligation loan approval.We welcome the opportunity to show you how effective we are at helping our clients obtain the money they need to succeed. Our professional staff is available for a Free Consultation.At Patiala legitimate company Pvt , contact us now 2% interest rate, both long and short term cash reply to us (Whats App) number: +919394133968 patialalegitimate515@gmail.com
ReplyDeleteMr Jeffery
Thanks for the valuable Content. I really learned a lot here. Do share more like this.
ReplyDeleteSales Force Testing
Salesforce Project Documentation
Aivivu chuyên vé máy bay, tham khảo
ReplyDeleteVe may bay di My
mua vé máy bay từ mỹ về việt nam
giá vé máy bay từ đức về việt nam
các chuyến bay từ nga về việt nam
giá thuê máy bay từ anh về việt nam
ve may bay tu phap ve viet nam
vé máy bay cho chuyên gia nước ngoài
Through this Digital Marketing Institute in Panchkula, you will become an expert in modules such as SEO, Social Media Marketing, PPC, Analytics, Content, Mobile, and Email Marketing. Our Social Media Marketing and PPC courses in Panchkula have trained end number of students. Work on real-world projects, learn the latest tools, and attend masterclasses led by the Google and Facebook certified team.
ReplyDelete- Get hands-on training on live projects!
- Upgrade your resume
- Get prepared for your dream job.
- 120+ hours of high-quality training.
- 10+ live projects.
- 25+ digital marketing tools and platforms.
Call: +91 9887046666
Location: SCO-9, First Floor, Sector-11, Panchkula, Haryana 134109
Authorization by government, state and neighborhood authorities is normal, and many bars, supermarkets, cafés and dance club are scrambling for a way of remaining one stride in front of those wearing phony ID cards to keep away from infractions.2022 fake id
ReplyDeletefake ids
Digital Marketing Training in Panchkula
ReplyDeleteDigital Marketing Training Institute in Panchkula
ReplyDeleteThrough this Digital Marketing Training Institute in Panchkula you will become an expert in modules such as SEO, Social Media Marketing, PPC, Analytics, Content, Mobile, and Email Marketing. Our Social Media Marketing and PPC courses in Panchkula have trained end number of students. Work on real-world projects, learn the latest tools, and attend masterclasses led by the Google and Facebook certified team.
ReplyDelete- Get hands-on training on live projects!
- Upgrade your resume
- Get prepared for your dream job.
- 120+ hours of high-quality training.
- 10+ live projects.
- 25+ digital marketing tools and platforms.
In straightforward words, the clients don't need to stress over the uninitiated or read mail that they needn't bother with any more. Low spam scores
ReplyDeleteNice blog, informative and knowledgeable content. Thanks for sharing with us.
ReplyDeleteBest Data Science Training in Hyderabad
I love your wp format, where did you get a hold of it? IRISH FAKE ID
ReplyDeleteThere is little distinction between the ranges of abilities moved by information modelers and those moved by database managers.college placement cells database
ReplyDeleteRecent Identity theft statistics and exactly what identity theft is. The five types of identity theft. How to help avoid being a victim of fraud. What are ways the thieves get personal information??? Medical Identity Theft can be every persons worst nightmare. Is it possible for somebody to get information and use it for child identity theft? fake id
ReplyDeleteWe are a leading Best SEO Company in Hyderabad who believes in human-first SEO strategies. Understanding the sentiment of your business needs, we realize that any business is driven by much more than just SERPs. It is driven by the right audience - real people, whose presence matters.
ReplyDeleteI think this is a standout amongst the most critical data for me. What"s more, i"m happy perusing your article. Be that as it may, ought to comment on some broad things fake id top
ReplyDeleteThank you for sharing an amazing & wonderful blog. This content is very useful, informative and valuable in order to enhance knowledge. Keep sharing this type of content with us & keep updating us with new blogs. Apart from this, if anyone who wants to join the Python Advanced training institute in Delhi, can contact 9311002620 or visit our website-
ReplyDeletehttps://www.htsindia.com/Courses/python/online-python-training-institute
eDigital is a trusted Best digital marketing agency in Hyderabad If you are looking to gain from an active local presence, we can help you grow across platforms and devices - helping you increase online visibility, website traffic, lead generation, local reputation etc.
ReplyDelete
ReplyDeleteBest glass manufacturer in Hyderabad!
i'd later to make perceived that this blog in actuality fulfilled me to appreciate it! much appreciated, each and every one proper case. thanks! Wishes For Sister Birthday
ReplyDeleteThis is a great post. Your blog is very informative I have learned a lot of information from your blog. We are top Website Development Company in India.
ReplyDeleteIf anyone is looking for Web Development services contact today: +91 9501406707
Nice blog.
ReplyDeleteDigital Marketing Course in Chandigarh holds together the professional modules of a comprehensive learning and experience which can land you in the arena of a shining career and wide professional knowledge.
Nice information thanks for sharing this.
ReplyDeleteData science course in Chandigarh
Happy to have read such a helpful post, which is quite helpful. It provided me with a wealth of knowledge, which I will definitely remember. Continue to share custom erp
ReplyDeletebest digital marketing agency in hyderabad and web design company weboptmise.in
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteagar aap ek student hai aur Hindi Matra or Hindi Vyakran se sambandhit jaankari chaahiye to hamare blog ko visit kar sakte hain.
ReplyDeleteDO YOU NEED FINANCES? ARE YOU LOOKING FOR FINANCES? ARE YOU LOOKING FOR FINANCING TO ENLARGE YOUR BUSINESS?via email:bullsindia187@gmail.com
ReplyDeleteDiscover the stunning bridal shower dresses by Ammara Khan, perfect for your barat or bridal shower. Explore our couture collection and find the dress of your dreams.
ReplyDelete