Thursday, April 20, 2017

Using Database.upsert with external ID field

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:

  1. If no record is found in table with provided External Id, then it will create record in table.
  2. If 1 record is found in table with provided External Id, then it will update record in table.
  3. 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:

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.



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

98 comments:

  1. AngularJS is a toolset for building the framework most suited to your application development. It is fully extensible and works well with other libraries. Every feature can be modified or replaced to suit your unique development workflow and feature needs. Read on to find out how.

    AngularJS Training in Chennai

    ReplyDelete
    Replies

    1. IEEE Final Year projects Project Centers in Chennai are consistently sought after. Final Year Students Projects take a shot at them to improve their aptitudes, while specialists like the enjoyment in interfering with innovation. For experts, it's an alternate ball game through and through. Smaller than expected IEEE Final Year project centers ground for all fragments of CSE & IT engineers hoping to assemble. Final Year Projects for CSE It gives you tips and rules that is progressively critical to consider while choosing any final year project point.

      Spring Framework has already made serious inroads as an integrated technology stack for building user-facing applications. Spring Framework Corporate TRaining the authors explore the idea of using Java in Big Data platforms.
      Specifically, Spring Framework provides various tasks are geared around preparing data for further analysis and visualization. Spring Training in Chennai


      The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

      Delete
  2. 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

    ReplyDelete
  3. Those guidelines additionally worked to become a good way to recognize that other people online have the identical fervor like mine to grasp great deal more around this condition.



    Digital marketing in chennai

    ReplyDelete
  4. I accept there are numerous more pleasurable open doors ahead for people that took a gander at your site.we are providing ReactJs training in Chennai.
    For more details: ReactJs training in Velachery | ReactJs training in chennai

    ReplyDelete
  5. 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?

    ReplyDelete

  6. This is an awesome post.Really very informative and creative contents. These concept is a good way to enhance the knowledge.I like it and help me to article very well.Thank you for this brief explanation and very nice information.Well, got a good knowledge.
    DedicatedHosting4u.com

    ReplyDelete
  7. Thanks for posting useful information.You have provided an nice article, Thank you very much for this one. And i hope this will be useful for many people.. and i am waiting for your next post keep on updating these kinds of knowledgeable things...Really it was an awesome article...very interesting to read..please sharing like this information.

    Thanks
    Cpa offers

    ReplyDelete
  8. Your post is very good. I got to learn a lot from your post. Thank you for sharing your article for us. it is amazing post
    what is seo
    types of seo

    ReplyDelete

  9. This is a fantastic idea! I like it a lot because it's super easy for the audience to see the value of opting in. wonderful and amazing post very use full your post thanks for sharing your article
    Android Application development
    Web application

    ReplyDelete
  10. Great 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.
    digital marketing company in chennai
    seo service in chennai
    web designing company in chennai
    social media marketing company in chennai

    ReplyDelete
  11. Nice blog thanks for sharing Is this a special day for you? Beautiful and fragrant flowers are sure to make it even more amazing of a day no doubt. This is why Karuna Nursery Gardens offers you the best rental plants in Chennai that too at drop dead prices.
    plant nursery in chennai
    rental plants in chennai
    corporate gardening service in chennai

    ReplyDelete
  12. Excellent blog thanks for sharing Buy the best beauty parlour products wholesale in Chennai at Pixies Beauty Shop. Thousands of global top-tier brands to choose from and friendly faces all over, we would love to make your Salon journey, one the world recognizes.
    beauty Shop in Chennai

    ReplyDelete
  13. keep up the good work. this is an Assam post. this to helpful, i have reading here all post. i am impressed. thank you. this is our digital marketing training center. This is an online certificate course
    digital marketing training in bangalore / https://www.excelr.com/digital-marketing-training-in-bangalore

    ReplyDelete
  14. Very useful blog thanks for sharing IndPac India the German technology Packaging and sealing machines in India is the leading manufacturer and exporter of Packing Machines in India.

    ReplyDelete
  15. 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.
    https://360digitmg.com/digital-marketing-training-in-hyderabad

    ReplyDelete
  16. nice blog
    great information.
    Makeup class
    is an integral part of Cosmetology and is a blooming industry in Beauty and Wellness Industry. At VLCC Institute, aspiring Cosmetologist can enroll into different Aesthetic Courses as per their requirements.

    ReplyDelete
  17. Very nice job... Thanks for sharing this amazing and educative blog post! ExcelR Digital Marketing Class In Pune

    ReplyDelete
  18. First of all I would like to thank you for writing this post I love both writing and reading new posts and I was just looking at new posts to see me something new, only then I saw your post and the rest of the post is praiseworthy.
    sofeeya.com

    ReplyDelete
  19. This 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.

    Data Science Institute in Bangalore

    ReplyDelete
  20. 360DigiTMG GunturJuly 8, 2020 at 8:40 AM

    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.

    data science course in guntur

    ReplyDelete
  21. Good post and informative. Thank you very much for sharing this good article, it was so good to read and useful to improve my knowledge as updated, keep blogging. Thank you for sharing wonderful information with us to get some idea about that content.
    oracle training in chennai

    oracle training institute in chennai

    oracle training in bangalore

    oracle training in hyderabad

    oracle training

    oracle online training

    hadoop training in chennai

    hadoop training in bangalore

    ReplyDelete
  22. Thanks for one marvelous posting! I enjoyed reading it; you are a great author. I will make sure to bookmark your blog and may come back someday. I want to encourage that you continue your great posts.

    python training in chennai

    python course in chennai

    python online training in chennai

    python training in bangalore

    python training in hyderabad

    python online training

    python training

    python flask training

    python flask online training

    python training in coimbatore

    ReplyDelete
  23. Fantastic post found to be very impressive to come across such an awesome blog. I really felt enthusiast while reading and enjoyed every bit of your content. Certainly, since this blog is being more informative it is an added advantage for the users who are going through this blog. Once again nice blog keep it up.

    360DigiTMG IoT Course

    ReplyDelete
  24. 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.…

    Azure 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

    ReplyDelete
  25. wow, great, I was wondering how to cure acne naturally. and found your site by google, learned a lot, now i’m a bit clear. I’ve bookmark your site and also add rss. keep us updated.
    business analytics training in Hyderabad

    ReplyDelete
  26. 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

    ReplyDelete
  27. Truly incredible blog found to be very impressive due to which the learners who ever go through it will try to explore themselves with the content to develop the skills to an extreme level. Eventually, thanking the blogger to come up with such an phenomenal content. Hope you arrive with the similar content in future as well.
    Digital Marketing Course in Raipur

    ReplyDelete
  28. Work is fantastic. Thank you very much for sharing this useful blog with us. My problem has been solved.

    1000 Social BookMarking Sites List

    ReplyDelete
  29. This is so helpful for me. Thanks alot for sharing.

    Trading for beginners

    ReplyDelete
  30. 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 
    Mr Jeffery

    ReplyDelete
  31. This Digital Marketing Course in Mohali transforms you into a complete Digital Marketer with expertise in modules like SEO, Social Media Marketing, PPC, Analytics, Content, Mobile, and Email marketing.
    We provide the Best training for Social Media Marketing and PPC course in Mohali and have trained over 10k students.
    Become industry-ready learning the latest tools, working on real-world projects, and attending Masterclasses from the Google and Facebook certified Team.
    Digital Marketing Course in Chandigarh

    ReplyDelete
  32. Thanks for the valuable Content. I really learned a lot here. Do share more like this.
    Sales Force Testing
    Salesforce Project Documentation

    ReplyDelete
  33. Thanks For Sharing such a wonderful article the way you presented is really amazing It was extraordinarily simple to discover my way around and amazingly clear, this is staggering!!!
    Best Digital Marketing Training Institutes

    ReplyDelete
  34. 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.

    - 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

    ReplyDelete
  35. 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
    fake ids

    ReplyDelete
  36. Wonderful blog found to be very impressive to come across such an awesome blog. I should really appreciate the blogger for the efforts they have put in to develop such an amazing content for all the curious readers who are very keen of being updated across every corner. Ultimately, this is an awesome experience for the readers. Anyways, thanks a lot and keep sharing the content in future too.

    Data Science Course in Bhilai

    ReplyDelete
  37. Impressive blog to be honest definitely this post will inspire many more upcoming aspirants. Eventually, this makes the participants to experience and innovate themselves through knowledge wise by visiting this kind of a blog. Once again excellent job keep inspiring with your cool stuff.

    Data Science Training in Bhilai

    ReplyDelete
  38. Thanks for your marvelous posting! I really enjoyed reading it, you could be a great author. I will be sure to bookmark your blog and definitely will come back in the foreseeable future. I want to encourage you to continue your great posts, have a nice afternoon! Online Digital Marketing Course with Placement

    ReplyDelete
  39. First You got a great blog .I will be interested in more similar topics.I commend you for your excellent report on the knowledge that you have shared in this blog.

    digital marketing training in hyderabad
    free digital marketing course in hyderabad

    ReplyDelete
  40. Through 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.



    - 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.

    ReplyDelete
  41. Excellent goods from you, man. I have understood your stuff previous to and you are simply extremely fantastic. I actually like what you’ve obtained right here, really like what you are saying and the way in which by which you are saying it. You are making it enjoyable and you still care to stay sensible. I can’t wait to read much more from you. This is really a wonderful site. Instrumentation and Control Engineering

    ReplyDelete
  42. I like your post. I appreciate your blogs because they are really good. Please go to this website for the Data Science Course: For Data Science Course Data Science course in Bangalore. These courses are wonderful for professionalism.

    ReplyDelete
  43. 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

    ReplyDelete
  44. Nice blog, informative and knowledgeable content. Thanks for sharing with us.
    Best Data Science Training in Hyderabad

    ReplyDelete
  45. Your blog is very helpful. I read this blog. Thanks For Sharing With Us. I will definitely go ahead and take advantage of this. You absolutely have wonderful blogs. Cheers for sharing with us your blog. For more learning go through skillslash.
    For Data Science Course Data Science course in Bangalore

    ReplyDelete
  46. I love your wp format, where did you get a hold of it? IRISH FAKE ID

    ReplyDelete
  47. There is little distinction between the ranges of abilities moved by information modelers and those moved by database managers.college placement cells database

    ReplyDelete
  48. Recent 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

    ReplyDelete
  49. Watch and Download world's famous Turkish action drama Kurulus Osman Season 3 in English on link below
    👇
    Kurulus Osman Season 3

    Kurulus Osman Season 3 Episode 1
    On link below
    Kurulus Osman Season 3 Episode 1

    Crypto trading course
    Join on link below
    Crypto quantum leap

    YouTube course
    Be a professional YouTuber and start your carrier
    Tube Mastery and Monetization by matt

    Best product for tooth pain ,
    Cavity ,
    Tooth decay ,
    And other oral issues
    Need of every home
    With discount
    And digistore money back guarantee
    Steel Bite Pro

    ReplyDelete
  50. We 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.

    ReplyDelete
  51. I 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

    ReplyDelete
  52. Welcome to the future! Financing made easy with Prof. Mrs. DOROTHY JEAN INVESTMENTS

    Hello, Have you been looking for financing options for your new business plans, Are you seeking for a loan to expand your existing business, Do you find yourself in a bit of trouble with unpaid bills and you don’t know which way to go or where to turn to? Have you been turned down by your banks? MRS. DOROTHY JEAN INVESTMENTS says YES when your banks say NO. Contact us as we offer financial services at a low and affordable interest rate of 2% for long and short term loans. Interested applicants should contact us for further loan acquisition procedures via profdorothyinvestments@gmail.com

    We invest in all profitable projects with cryptocurrencies. I'm here to share an amazing life changing opportunity with you. its called Bitcoin / Forex trading options, Are you interested in earning a consistent income through binary/forex trade? or crypto currency trading. An investment of $100 or $200 can get you a return of $2,840 in 7 days of trading and you get to do this from the comfort of your home/work. It goes on and on The higher the investment, the higher the profits. Your investment is safe and secured and payouts assured 100%. if you wish to know more about investing in Cryptocurrency and earn daily, weekly OR Monthly in trading on bitcoin or any cryptocurrency and want a successful trade without losing Contact MRS.DOROTHY JEAN INVESTMENTS Email profdorothyinvestments@gmail.com


    YOURS IN SERVICE
    Mrs. Dorothy Pilkenton Jean
    Financial Advisor on Bank Instruments,
    Private Banking and Client Services
    Email Address: profdorothyinvestments@gmail.com
    Operation: We provide Financial Service Such As Bank Instrument
    From AA Rate Banks, Cash Loan,BG,SBLC,BOND,PPP,MTN,TRADING,FUNDING MONETIZING etc.

    ReplyDelete
  53. Thanks for sharing this valuable information, we also provide instagram video download and,
    really appreciate your hard work and good research that help us in for of your good valuable article. Keep updating us with your awesome content.

    ReplyDelete
  54. Welcome to the future! Financing made easy with Prof. Mrs. DOROTHY JEAN INVESTMENTS

    Hello, Have you been looking for financing options for your new business plans, Are you seeking for a loan to expand your existing business, Do you find yourself in a bit of trouble with unpaid bills and you don’t know which way to go or where to turn to? Have you been turned down by your banks? MRS. DOROTHY JEAN INVESTMENTS says YES when your banks say NO. Contact us as we offer financial services at a low and affordable interest rate of 2% for long and short term loans. Interested applicants should contact us for further loan acquisition procedures via Whatsapp Number +1(541)279-1406 Email profdorothyinvestments@gmail.com

    We invest in all profitable projects with cryptocurrencies. I'm here to share an amazing life changing opportunity with you. its called Bitcoin / Forex trading options, Are you interested in earning a consistent income through binary/forex trade? or crypto currency trading. An investment of $100  or  $200 can get you a return of $2,840 in 7 days of trading and you get to do this from the comfort of your home/work. It goes on and on The higher the investment, the higher the profits. Your investment is safe and secured and payouts assured 100%. if you wish to know more about investing in Cryptocurrency and earn daily, weekly OR Monthly in trading on bitcoin or any cryptocurrency and want a successful trade without losing Contact MRS.DOROTHY JEAN INVESTMENTS  Email profdorothyinvestments@gmail.com


    YOURS IN SERVICE
    Mrs. Dorothy Pilkenton Jean
    Financial Advisor on Bank Instruments,
    Private Banking and Client Services
    Whatsapp Number +1(541)279-1406
    Email Address: profdorothyinvestments@gmail.com
    Operation: We provide Financial Service Such As Bank Instrument
    From AA Rate Banks, Cash Loan,BG,SBLC,BOND,PPP,MTN,TRADING,FUNDING MONETIZING etc.

    ReplyDelete
  55. I like your post. I appreciate your blogs because they are really good. Please go to this website for Data Science course in Bangalore. These courses are wonderful for professionals.

    ReplyDelete
  56. Thank 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-
    https://www.htsindia.com/Courses/python/online-python-training-institute

    ReplyDelete
  57. Thanks for sharing your blog. In this Blog you have given Informative Information which is very important for users.WHMCS Theme is a creative and professional theme that can be used for any kind of website like business, agency, corporate, events, arts, portfolio, design and much more. The theme comes with a powerful admin panel where users can change fonts, colors and other aspects of their website by using the live customizer.

    ReplyDelete
  58. I have entryway all the criticism and clues posted by involving the guests for this article are no doubt appropriate humored,we will look for your connecting article precisely by utilizing yourself. thanks! Virtual Audio Cable Full

    ReplyDelete
  59. 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
  60. An every single one top notch blog pitch. we are in truth appreciative on your blog call. you'll find various strategies in the wake of voyaging your say. thanks! Easeus Data Recovery Wizard Serial

    ReplyDelete
  61. 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

    ReplyDelete
  62. Thanks for sharing this valuable information,we provide pinterest video download which helps to get more ideas to write more quality content.

    ReplyDelete