SFDCian – Best Salesforce Consultant & Architect

Apex error – ‘List has no rows for assignment to SObject’

The error “List has no rows for assignment to SObject” occurs when query doesn’t return any rows.

Resolution   

While a SELECT normally returns an array/list, these statements are using the shorthand syntax that assumes only one row is returned. What’s not obvious is that it also assumes that exactly one row is returned! Although this is unlikely to occur for Contact, it is highly likely to occur for any custom objects you create, especially when a WHERE statement is used that might return zero rows, such as: 

The above code will fail if there is no Player__c record with the matching username. It doesn’t actually return a null.  It would be safer to do the following:

It’s one of those situations for which you would not normally think of creating a test, so it’s safer to just avoid the possibility.

Related Posts

Salesforce: opportunity clone for each opportunity contact role along with opportunity products, are you building lightning app with locker services.

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

List has no rows for assignment to SObject - Controller Extension

I've spent several hours today trying to figure this out and running through several online resources here and SFDC forums to no avail.

I keep getting the following error:

List has no rows for assignment to SObject An unexpected error has occurred. Your development organization has been notified.

Here is my code:

VisualForce Markup:

  • controller-extension

Adrian Larson's user avatar

  • Try instantiating the list sAddProd instead, as you have for sap list –  Girbot Commented Jun 13, 2017 at 19:35
  • sap.size() will never be null. –  sfdcfox ♦ Commented Jun 13, 2017 at 19:39

You should just use cntrl.getId() instead. Calling cntrl.getRecord() only pulls in the fields included on your page. Everywhere you have this.sub.Id , change it to cntrl.getId() .

That said, you are never guaranteed to have a child record. The standard approach to querying for a single record whose existence is not guaranteed is to query to a list, then check if it is empty:

  • Hi @AdrianLarson, I did as you said, made those changes, minus the getId. It doesn't give the error, still works, but those that don't have a child record show data. Interesting, I'm sure it has to do with getId. Side note, I tried your method getId and it gave me an issue. Not sure if I should write a separate question for that, or I can try to add it again and let you know what error it gave me. Appreciate the tips! –  Louis HM Commented Jun 13, 2017 at 19:57
  • @LouisHM Did you try to use controller.getId() instead of cntrl.getId() ? My post is actually crafted to discourage copy pasta. –  Adrian Larson ♦ Commented Jun 13, 2017 at 20:01
  • I too am still learning. I've moved this conversation to chat so we can continue it without cluttering the comments. –  Adrian Larson ♦ Commented Jun 13, 2017 at 20:08
  • This is what I get --> ***classes/SubscriptionAddProdExtension.cls: Incompatible types since an instance of String is never an instance of Subscription__c (Line: 12, Column: 20) *** –  Louis HM Commented Jun 13, 2017 at 20:09

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged apex controller-extension ..

  • The Overflow Blog
  • Where does Postgres fit in a world of GenAI and vector databases?
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites

Hot Network Questions

  • Do the amplitude and frequency of gravitational waves emitted by binary stars change as the stars get closer together?
  • Has the US said why electing judges is bad in Mexico but good in the US?
  • How to remove obligation to run as administrator in Windows?
  • My school wants me to download an SSL certificate to connect to WiFi. Can I just avoid doing anything private while on the WiFi?
  • Dress code for examiner in UK PhD viva
  • Expected number of numbers that stay at their place after k swaps
  • Parse Minecraft's VarInt
  • Safety pictograms
  • Chromatic homotopy + algebraic geometry =?
  • Why doesn't the world fill with time travelers?
  • Are carbon fiber parts riveted, screwed or bolted?
  • Using conditionals within \tl_put_right from latex3 explsyntax
  • What happens if all nine Supreme Justices recuse themselves?
  • about flag changes in 16-bit calculations on the MC6800
  • What is an intuitive way to rename a column in a Dataset?
  • Completely introduce your friends
  • Optimal Bath Fan Location
  • Why was this lighting fixture smoking? What do I do about it?
  • Relation between stopping times and their filtrations
  • Series with odd numbers
  • How did Oswald Mosley escape treason charges?
  • How can I get an Edge's Bevel Weight attribute value via Python?
  • How can I delete a column from several CSV files?
  • DATEDIFF Rounding

apex handle list has no rows for assignment to sobject

Salesforce – List has no rows for assignment to SObject

if you using following code in Apex and Error should throw like “List has no rows for assignment to SObject”.

Account a = [Select name from acoount where id =: strId];

Try to avoid the error following code in you Apex.

List<Account> lstAccount = [Select Id, name from acoount where id =: strId];

apex handle list has no rows for assignment to sobject

Sakthivel Madesh

3x Salesforce MVP | Platform Champion | 22x Salesforce Certified | MuleSoft Certified | All Star Ranger | TechForce Services | Sydney | Australia

What are the Granting Access available in Salesforce Event Calendar

How to return a pagereference to create a sobject in salesforce, you may also like, upgrading apex classes for custom metadata access: a..., congratulations to the 2024 class of salesforce mvps,..., unlock your salesforce certification with free vouchers in..., free salesforce certification days webinars – december 2023, spring 24 – dynamic forms supported the related..., salesforce flow – repeater (beta) screen components –..., salesforce flows & reactive screen components: the next..., free salesforce certification days webinars – november 2023, join the salesforce community sprint: accelerating innovation together, elevate your salesforce journey with free accredited professional..., leave a comment cancel reply.

Save my name, email, and website in this browser for the next time I comment.

Get the Reddit app

This is an unofficial (no salesforce sponsorship) forum to discuss getting certified and building on salesforce platforms (force.com, heroku, exacttarget, slack, etc.)

Test class fail System.QueryException: List has no rows for assignment to SObject

Hi guys, I made 4 apex classes + 4 tests classes (based on account,contact,opp and lead)

All the classes work and 3 of the test pass, my contact test class fail with the error System.QueryException: List has no rows for assignment to SObject

The test code:

any suggestions?

By continuing, you agree to our User Agreement and acknowledge that you understand the Privacy Policy .

Enter the 6-digit code from your authenticator app

You’ve set up two-factor authentication for this account.

Enter a 6-digit backup code

Create your username and password.

Reddit is anonymous, so your username is what you’ll go by here. Choose wisely—because once you get a name, you can’t change it.

Reset your password

Enter your email address or username and we’ll send you a link to reset your password

Check your inbox

An email with a link to reset your password was sent to the email address associated with your account

Choose a Reddit account to continue

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Can somebody explain the error 'System.QueryException: List has no rows for assignment to SObject'?

everyone. Im new to apex, I was trying for code coverage of atleast 75% on my batch apex code through test class. But im getting the error " System.QueryException: List has no rows for assignment to SObject ". Execute method is not covering in the code. Will anyone point out whats wrong with the testclass?

Batch Apex Class:-

Test class:-

Yash Hatekar's user avatar

2 Answers 2

In your test class you have initiated Account but didn't insert, and in Line 21 you are querying the fields based on that account id which doesn't exists. Because of this you are getting the QueryException.

Babul Jha's user avatar

Your test is weird. You select existing accounts. There are none. You have a piece of batch copy-pasted - why? Even if it'd work - how would you distinguish between what the test did and what the batch did?

You'd have to insert some accounts first. I think the error you get is from test's line 21 but the problems (including "Execute method is not covering in the code") are earlier.

Next time include the test's code too, screenshots are painful to retype.

I think you need something like this (there might be typos!)

Edit : another user suggested following edit to my post. I don't agree with it but I'll put it here to preserve the idea and he can always post his own answer with improvements/reasoning.

https://stackoverflow.com/users/6718505/waldemar-liedle

All Assets (sic) in a Loop is a Bad Idea. When no Accounts are Inserted, the Test would still succeed. I would also Check something Outside Loop

  • I don't think it matters because accounts are inserted earlier in the test. You'd need to completely mess the batch job up so it'd start deleting accounts for this query to fail finding any.
  • normally tests see only data that was inserted during test so it's not like it'll query thousands here (you'd run into other problems like "in test there can be only 1 execute()" so 200 accounts max)
  • in extreme cases querying all records to a List instead of looping through query (silently calling queryMore() when needed) will eat lots of memory

eyescream's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged salesforce apex apex-code or ask your own question .

  • The Overflow Blog
  • Where does Postgres fit in a world of GenAI and vector databases?
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites
  • What does a new user need in a homepage experience on Stack Overflow?
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • Staging Ground Reviewer Motivation

Hot Network Questions

  • Does the order of ingredients while cooking matter to an extent that it changes the overall taste of the food?
  • Is integration physical, but differentiation is not?
  • Do metal objects attract lightning?
  • Purpose of burn permit?
  • Why does a rolling ball slow down?
  • Is Intuition Indispensable in Mathematics?
  • Is there a phrase for someone who's really bad at cooking?
  • Living in Germany (6 months>), working remotely for a French company- Where to pay taxes?
  • How much payload could the Falcon 9 send to geostationary orbit?
  • Walk or Drive to school?
  • What explanations can be offered for the extreme see-sawing in Montana's senate race polling?
  • Is tipping your personal trainer considered weird in South India?
  • Who was the "Dutch author", "Bumstone Bumstone"?
  • Are quantum states like the W, Bell, GHZ, and Dicke state actually used in quantum computing research?
  • Reusing own code at work without losing licence
  • Is this a new result about hexagon?
  • Parody of Fables About Authenticity
  • Why there is no article after 'by'?
  • My school wants me to download an SSL certificate to connect to WiFi. Can I just avoid doing anything private while on the WiFi?
  • Why doesn't the world fill with time travelers?
  • Raspberry Screen Application
  • Could someone tell me what this part of an A320 is called in English?
  • Why is "on " the optimal preposition in this case?
  • What rule or standard is used to assign a SOT number to a chip housing?

apex handle list has no rows for assignment to sobject

IMAGES

  1. apex

    apex handle list has no rows for assignment to sobject

  2. User Apex Error

    apex handle list has no rows for assignment to sobject

  3. 【Apex】List has no rows for assignment to SObjectのエラーと解決策について

    apex handle list has no rows for assignment to sobject

  4. apex

    apex handle list has no rows for assignment to sobject

  5. Understanding 'List has no rows for assignment to SObject' in a trigger

    apex handle list has no rows for assignment to sobject

  6. Trailhead : Apex Integration Services System.QueryException: List has

    apex handle list has no rows for assignment to sobject

VIDEO

  1. How to create display only, file browse, hidden, listmanager and shuttle item in oracle apex

  2. Zach's friend list has no room for Jared

  3. SOLOS MODE TIER LIST

  4. This was the easiest Prestige Skin to unlock in Apex Legends

  5. Getting 6000 Damage As A Movement Player

  6. MUph2024 TOP 5 STANDOUTS during the PRELIMINARY INTERVIEW!

COMMENTS

  1. Apex error 'List has no rows for assignment to SObject'

    What's not obvious is that it also assumes that exactly one row is returned! Although this is unlikely to occur for Contact, it is highly likely to occur for any custom objects you create, especially when a WHERE statement is used that might return zero rows, such as:

  2. apex

    If you get more than 1 row and attempt to assign that to your Accountx variable you will get the opposite of your original problem - System.QueryException: List has more than 1 row for assignment to SObject! So one way of guarding against this would be to use Account accountx = [SELECT Id FROM Account LIMIT 1]'. - frup42.

  3. custom object

    This is resulting in no records being returned and Salesforce throwing the System.QueryException: List has no rows for assignment to SObject. Note that this is unlike some other programming languages where you may expect the query to just set your sObject to null. Salesforce's documentation for System.QueryException states it is thrown when ...

  4. I'm getting "List has no rows for assignment to SObject" error on a

    If the query doesn't return any rows you will get the "List has no rows for assignment to SObject" exception. Instead, assign the results to a list of sObjects and check the size of the list. Then only use the first record in the list if it is present.

  5. System.QueryException: List has no rows for assignment to SObject

    First, the 'account' instance must be initialised. Second, just make sure the ID is being passed in the page's URL correctly. In the ApexPages.currentPage ().getParameters ().get ('id') statement, the .get ('id') part is case sensitive. So please make sure, that is how you have passed your ID in the URL. Third, there should be a record in ur ...

  6. apex

    System.QueryException: List has no rows for assignment to SObject. Ask Question Asked 3 years, 11 months ago. Modified 3 years, 11 months ago. Viewed 3k times ... Apex. public class UpdateListofOppty { public Opportunity opportunities {get;set;} public Id recId{get;set;} public UpdateListofOpporunity(ApexPages.StandardSetController sc){ recId ...

  7. Help with error: List has no rows for assignment to SObject

    Tour Start here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the workings and policies of this site

  8. Apex error

    What's not obvious is that it also assumes that exactly one row is returned! Although this is unlikely to occur for Contact, it is highly likely to occur for any custom objects you create, especially when a WHERE statement is used that might return zero rows, such as:

  9. List has no rows for assignment to SObject: ERROR APEX

    Apex Testing Error: System.QueryException: List has no rows for assignment to SObject Hot Network Questions Seven different digits are placed in a row.

  10. apex

    1. You should just use cntrl.getId() instead. Calling cntrl.getRecord() only pulls in the fields included on your page. Everywhere you have this.sub.Id, change it to cntrl.getId(). That said, you are never guaranteed to have a child record. The standard approach to querying for a single record whose existence is not guaranteed is to query to a ...

  11. System.QueryException: List has no rows for assignment to SObject

    If it doesn't, you will get the 'List has no rows for assignment to SObject' exception again. Reply reply More replies. Sammy-Speed ... No. Leaving out the 'limit 1' is fine if the query returns exactly one record - apex will let you skip the whole array thing. Reply reply

  12. Vague "List has No Rows for Assignment to SObject" Error

    List<sObject> // [SELECT Id FROM Contact LIMIT 100] (returns a list of 100 Contacts) sObject // [SELECT Id FROM Contact LIMIT 1] (returns a single Contact) Integer // [SELECT Count() FROM Contact] (returns how many Contacts exist in your org) There is a gotcha here, that you ran up against.

  13. Apex error 'List has no rows for assignment to SObject'

    General Information. We use three kinds of cookies on our websites: required, functional, and advertising. You can choose whether functional and advertising cookies apply. Click o

  14. Error 'List has no rows for assignment to SObject' in Salesforce CPQ

    Lack of access to the Opportunity object throws List has no rows for assignment to SObject' since our code queries for the Primary Quote on that opportunity. Additional Resources SEE ALSO

  15. Document Generation Error- "List has no rows for assignment to SObject

    Open the active template in the Document Template tab (NOT the Docgen Document Template) Add ContentVersionId field to the layout if it is not present already; Go to the Id in Salesforce to check Sharing Settings. If the ContentVersionId file is not shared, share it manually with the library/user.

  16. Salesforce

    Save my name, email, and website in this browser for the next time I comment.

  17. Test class fail System.QueryException: List has no rows for assignment

    Hi guys, I made 4 apex classes + 4 tests classes (based on account,contact,opp and lead) All the classes work and 3 of the test pass, my contact test…

  18. Can somebody explain the error 'System.QueryException: List has no rows

    Im new to apex, I was trying for code coverage of atleast 75% on my batch apex code through test class. ... System.QueryException: List has no rows for assignm... Skip to main content. Stack Overflow. About; Products ... List has no rows for assignment to SObject ". Execute method is not covering in the code. Will anyone point out whats wrong ...

  19. Common fix to a "Error: List has no rows for assignment to SObject

    Applications (and the other AMS Stages) has a Master-Detail Object Relationship within the Salesforce Data model to Job Order. This means the Record Type of the AMS Stages is acquired from the Job Order.