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

List has no rows for assignment to SObject error although query returns rows

I'm a bit new to apex and I am trying to display a selectList in a visualforce page using a custom controller i built.

I get a "List has no rows for assignment to SObject" error when trying to preview the visualforce page, but running the query in the developer console, returns the rows.

here is my page:

and my controller:

Just to clarify the query i'm referring to is the query in getProductsLov() .

My API version is 40 and i am working in a sandbox environment.

  • visualforce

RealGigex's user avatar

Impossible. If you're getting "list has no rows to assign to sObject" it means you're assigning to single object. This eliminates getProductsLov (unless you didn't post whole code) because there you assign to a list.

Humo(u)r me and System.debug(JSON.serializePretty(ApexPages.currentPage().getParameters())); in your constructor before firing that query...

You're viewing the page with valid Account Id passed in the URL? And that Account is visible for your current user? If the page is account-specific, try using <apex:page standardController="Account" extensions="BpmIcountPayment">... (you'll have to provide a different constructor in apex first). This could simplify your code a lot.

eyescream's user avatar

  • You are right! The page displays correctly after adding a valid "id" parameter to the url. Thank you! –  RealGigex Commented Feb 7, 2018 at 8:51

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 visualforce apex soql or ask your own question .

  • The Overflow Blog
  • Where developers feel AI coding tools are working—and where they’re missing...
  • He sold his first company for billions. Now he’s building a better developer...
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Preventing unauthorized automated access to the network
  • Should low-scoring meta questions no longer be hidden on the Meta.SO home...
  • Announcing the new Staging Ground Reviewer Stats Widget

Hot Network Questions

  • Model files not opening with Cura after removing old version
  • A military space Saga with a woman who is a brilliant tactician and strategist
  • Do early termination fees hold up in court?
  • How important exactly is the Base Attack Bonus?
  • What is the simplest formula for calculating the circumference of a circle?
  • How to filter based on multiple geo co-ordinates with Sitecore Search
  • How do I avoid getting depressed after receiving edits?
  • How similar were the MC6800 and MOS 6502?
  • Easily unload sand/gravel from pickup truck
  • Will a car seat fit into a standard economy class seat on a plane?
  • Meaning of "wordplay from definition"
  • Image localisation and georeference
  • Alien Weekends!
  • How old was Abraham when Rebecca (Isaac's wife) was born?
  • Why does Voyager use consumable hydrazine instead of reaction wheels that only rotate when moving the spacecraft?
  • Why would elves care what happens to Middle Earth?
  • How can I draw a wedge of a cylinder?
  • Can I breed fish in Minecraft?
  • Why did the Jews call themselves "children of Abraham" not "children of Jacob"?
  • Harmonizing modes other than major and minor
  • Is there a faster way to find the positions of specific elements in a very large list?
  • When can I book German train tickets for January 2025?
  • Soldering a thermal fuse. 92°C
  • Both one and two hashes in macro parameter seem to work

apex soql list has no rows for assignment to sobject

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.

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

EDIT: Is there a recommended way for a VF email template that uses a VF component to display in the SFDC UI such that you don't get the error message "Error occurred trying to load the template for preview: List has no rows for assignment to SObject. Please try editing your markup to correct the problem"

when saving the template? As the original problem description states below, I get this message when saving the VF template. The only workaround (see component controller code) that seems to work for me is to read a "test" opportunity such that the VF template has something to display, but this seems to be a complete hack - and I'm not guaranteed to have a "test" opportunity in any environment.

ORIGINAL: I'm trying to use a component in a VF email template that queries opportunity line items from an opportunity lookup in a custom object. I get the error "List has no rows for assignment to SObject" if I don't query at least one opportunity object, which is the basis of my question.

The gist of the VF template is this;

The Component looks like this;

And the controller is this;

But what I don't like is I'm burning an extra SOQL statement just for preview of the VF page. If strOptID is null (during preview) I have to query an "artificial" opportunity that "should" be there ("%Test%").....

I don't like this solution and I'm sure there's a better way, and I was hoping someone might point me to a more appropriate way to accomplish this.

Thanks in advance.

  • visualforce
  • visualforce-component

Matt Lacey's user avatar

  • 1 possible duplicate of Help with error: List has no rows for assignment to SObject –  Daniel Ballinger Commented Mar 2, 2015 at 18:31
  • 4 I've voted to close this question as the general error has been covered previously in other questions. As a general rule, don't assign the results of a SOQL query to a singular sObject. 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. –  Daniel Ballinger Commented Mar 2, 2015 at 18:33
  • Hi all, that link doesn't cover components - I vote that it's a different problem. I've searched "VF Component" and "No Rows" and this is the only question. –  user2223 Commented Mar 2, 2015 at 18:37
  • 1 I don't believe the exception differs because it is a component. Can you indicate which line in your example code is throwing the exception? Maybe you would like to rework your question to emphasis that that the issue is getting a default record in preview mode rather than the resulting exception. –  Daniel Ballinger Commented Mar 2, 2015 at 18:47
  • 2 The problem is doing this in Apex: Opportunity lo = [SELECT Id, Name FROM Opportunity WHERE Id = :strOptID LIMIT 1]; . You need to assign the SOQL results to a List<Opportunity> , check the resulting List size and then get lo from the first record in the list. If the list is empty you need to return. –  Daniel Ballinger Commented Mar 2, 2015 at 18:56

3 Answers 3

General rule - don't return result of SOQL to an object, but return it to a list of objects. After querying items, check the list. Don't do

In your case Opportunity. But you have two places where this error may appear.

Andrii Muzychuk's user avatar

I would suggest that you refactor your queryDetailData method to query into a list instead of a single record. Then, if the resulting size of the List is 0, then set a boolean rendered flag to false, thus hiding the component, and preventing the error from occurring when you are in preview mode.

JimRae's user avatar

  • Thanks JimRae. Great idea about the rendered flag, but since it's an email that's related to one record, (Limit 1), can't I still just check for the return opportunity being null after the SOQL? Thanks again. –  user2223 Commented Mar 2, 2015 at 21:39
  • You could, but you may still have the no results error. The other way to handle this would be to put the SOQL query in a try/catch block, then catch the Query Exception and as long as it is "no rows" related, you could set the no render flag, or handle the optional processing another way of your choosing. –  JimRae Commented Mar 2, 2015 at 22:19

tempOppty is a single sObject. May be the soql is not assigning any record to this. You would want to convert this into a list and proceed accordingly.

the_phantom's user avatar

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged visualforce visualforce-component ..

  • The Overflow Blog
  • Where developers feel AI coding tools are working—and where they’re missing...
  • He sold his first company for billions. Now he’s building a better developer...
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Preventing unauthorized automated access to the network

Hot Network Questions

  • Model files not opening with Cura after removing old version
  • Expected value of a matrix = matrix of expected value?
  • How is the universe able to run physics so smoothly?
  • Is it common in modern classical music for timpani to play chromatic passages?
  • How do you tell someone to offer something to everyone in a room by taking it physically to everyone in the room so everyone can have it?
  • Is Mankiw 's answer really correct? The expected benefit from installing the traffic light. ("Principles of Economics 9e" by Mankiw.)
  • FIFO capture using cat not working as intended?
  • Unable to re-use an old deleted Apple Account (aka Apple ID)
  • What should you list as location in job application?
  • Harmonizing modes other than major and minor
  • Azure SQL Database CLR functions are working
  • Purpose of sleeve on sledge hammer handle
  • Does this ZFC+V=L like theory, have a limit on large cardinal properties?
  • Why would elves care what happens to Middle Earth?
  • A scrambled word which can't be guessed without all of its letters
  • Can I breed fish in Minecraft?
  • Why the proper acceleration is zero during free fall?
  • When can I book German train tickets for January 2025?
  • How was the year spoken in late 1800s England?
  • Place some or all of the White Chess pieces on a chessboard in such a way that none of them can legally move
  • Short story about a space traveller on a planet of people, each immensely talented
  • Cache tags not bubbling up correctly in blocks
  • Soldering a thermal fuse. 92°C
  • Does a ball fit in a pipe if they are exactly the same diameter?

apex soql list has no rows for assignment to sobject

IMAGES

  1. apex

    apex soql list has no rows for assignment to sobject

  2. Getting "System.QueryException: List has no rows for assignment to

    apex soql list has no rows for assignment to sobject

  3. User Apex Error

    apex soql list has no rows for assignment to sobject

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

    apex soql list has no rows for assignment to sobject

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

    apex soql list has no rows for assignment to sobject

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

    apex soql list has no rows for assignment to sobject

VIDEO

  1. LA County Jail : "Mr Never Sit Still" Speaks on Jail Politics, Non Affiliate Fridays AND MORE!!!

  2. ࣪ ⋆​​୨୧˚ ℋℴ𝓁𝓁𝓎𝓌ℴℴ𝒹𝓈 favourite girl

  3. Day 01 Part 1: Learn SOQL (Check description) Salesforce Apex

  4. Aula 1

  5. Write SOQL Queries || Apex Basics & Database

  6. Apex SOQL and SOSL in Salesforce Part 1

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

    When test cases are run, you should create test data. Since you do not have any while condition, all you have to do while creating test data is put values in the mandatory fields. Insert the record via code and use the ID from there itself. The query in Test class should refer to this variable that hold the ID and not a hardcoded value of ID.

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

  5. salesforce

    Impossible. If you're getting "list has no rows to assign to sObject" it means you're assigning to single object. This eliminates getProductsLov(unless you didn't post whole code) because there you assign to a list.. Humo(u)r me and System.debug(JSON.serializePretty(ApexPages.currentPage().getParameters())); in your constructor before firing that query...

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

  7. apex

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

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

  9. SOQL For Loops

    SOQL for loops can process records one at a time using a single sObject variable, or in batches of 200 sObjects at a time using an sObject list:. The single sObject format executes the for loop's <code_block> one time per sObject record. Consequently, it's easy to understand and use, but is grossly inefficient if you want to use data manipulation language (DML) statements within the for loop ...

  10. apex

    SOQL queries can be used to assign a single sObject value when the result list contains only one element. When the L-value of an expression is a single sObject type, Apex automatically assigns the single sObject record in the query result list to the L-value. A runtime exception results if zero sObjects or more than one sObject is found in the ...

  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. ... apex will let you skip the whole array thing. Reply reply ... In general, I make a habit to do soql directly on the for statement. In this case, it doesn't really matter since it's a max of one record, but it's still a good habit. ...

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

    Make sure the affected user has 'Salesforce CRM Content User' enabled. This must be checked on their User Detail page in Setup. The affected user should be provided access to the Docgen Document Template Library.

  13. SOQL and SOSL Queries

    The 4,000 characters limit for WHERE clause strings doesn't apply to SOQL queries in Apex if the WHERE clause includes the IN operator. For a full description of SOSL query syntax, see the Salesforce SOQL and SOSL Reference Guide. SOQL queries can be used to assign a single sObject value when the result list contains only one element.

  14. apex

    2. following apex code. timeStr = 'Not yet updated.'; timeStr = d.format('MMMMM dd, yyyy hh:mm a z'); is giving me System.QueryException: List has no rows for assignment to SObject if there are no (zero) rows in DatadoctorStatus__c SObject. By the way this is expected behavior.

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

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