Stack Exchange Network
Stack Exchange network consists of 181 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It only takes a minute to sign up.
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
- 1 possible duplicate of Help with error: List has no rows for assignment to SObject – Daniel Ballinger 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 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 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 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 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.

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.

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

Your Answer
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 , privacy policy and cookie policy
Not the answer you're looking for? Browse other questions tagged visualforce visualforce-component or ask your own question .
- The Overflow Blog
- How to position yourself to land the job you want
- Building an API is half the battle: Q&A with Marco Palladino from Kong
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
- The Stack Exchange reputation system: What's working? What's not?
Hot Network Questions
- How were rackmount workstations wired-up to mice, keyboards, monitors, etc?
- Best way to highlight the main result in a mathematical paper
- In a civil trial, can a party “call” its opponent’s witnesses in making its case?
- Is there a RAW or optional rule for how a player could discover what type of skill check needs to be made?
- Truncated floor symbol
- (-40)-(40)V P Channel Based Reverse Polarity Protection
- What filter is used on this image?
- Stacked NumberLinePlot?
- Do cell-phone base station antennas emit the same power as cell phones?
- The mystery behind the /Applications folder on Ventura
- When does a character get temporary HP from the Shepherd druid's Bear Spirit Totem?
- Cut locus for simply connected manifolds
- Would these solar systems be stable?
- Detect round trips on a hyperbolic grid
- Implementation of a shared pointer constructors and destructor
- Why does Windows 11 PowerShell or terminal lack Linux command line tools?
- How was altitude calculated before the invention of the altimeter?
- Is it traversable?
- Finding a career as a researcher without any PhD, work experience, and/or relevant academic degree
- Why is the Declaration of Independence not held as legally binding, under Art VI, cl I, of the U.S. Constitution?
- How did asteroid (7482) 1994 PC1 get its "face"? Is it reconstructed from optical or radar imaging, or something else?
- Is it insecure to sign the value 0 with ElGamal?
- SSL issue captures Facebook app send out traffic
- Is the Garmin G1000's heading indicator based on a Magnetic compass?
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .
- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- About the company
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.
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

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.
- You are right! The page displays correctly after adding a valid "id" parameter to the url. Thank you! – RealGigex Feb 7, 2018 at 8:51
Your Answer
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 , privacy policy and cookie policy
Not the answer you're looking for? Browse other questions tagged salesforce visualforce apex soql or ask your own question .
- The Overflow Blog
- How to position yourself to land the job you want
- Building an API is half the battle: Q&A with Marco Palladino from Kong
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
- The Stack Exchange reputation system: What's working? What's not?
- Launching the CI/CD and R Collectives and community editing features for...
- The [amazon] tag is being burninated
- Temporary policy: ChatGPT is banned
- Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2
Hot Network Questions
- Detect round trips on a hyperbolic grid
- Is it possible to change the TeX hyphenation rules for Ecclesiastical Latin?
- Finding a career as a researcher without any PhD, work experience, and/or relevant academic degree
- Dupin cyclide as the stereographic projection of a Hopf torus
- Displaying Hasse diagram (directed edges in graph pointing upwards)
- Why is the Declaration of Independence not held as legally binding, under Art VI, cl I, of the U.S. Constitution?
- Stacked NumberLinePlot?
- How can I tell if Ubuntu driver is using integrated graphics GPU to hardware decode HEVC when playing videos using VLC?
- Firefox very distorted, unusable
- Can a 13-year-old in the UK accept freelance work?
- Netgear DGND3800B limiting FTTH speed to 300Mbps
- What if a student doesn't understand a question because of differences in dialect?
- What's the 'right' number of parameters for an ARIMA model?
- Is the cabin pressure "worse" at the back of the cabin than in front?
- I need to have each line of a file run in a subshell of its own
- "Hierba" or "Yerba" - which is gramatically correct?
- Mapping Passing Through Point
- Preserve layout while using figures in columns in overlay
- COVID repeated test
- In Acts 8:32–33 was the Ethiopian eunuch reading a Septuagint scroll or a Hebrew scroll?
- Was Freemasonry such a big problem in 1980s UK policing?
- Can the positive root of this polynomial be expressed elementarily?
- Most polyominoes in an 8x8 grid
- Is there a specific field which addresses how to develop new software specifically for natural sciences?
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

- My Developer Account >
- Create Account>
- My Settings>
- All Developer Centers
- Community Cloud
- Einstein Analytics
- Einstein Platform
- Embedded Service SDK for Mobile
- Heroku Developer Center
- Integration and APIs
- Lightning Apps
- Lightning Flow
- Marketing Cloud
- Mobile Developer Center
- Mulesoft Developer Center
- Pardot Developer Center
- Quip Developer Center
- Salesforce DX
- Service Cloud
- Lightning Component Library
- Lightning Design System
- Lightning Aura Components
- All Documentation
- Certification
- Sample Gallery
- Video Gallery
- Events and Webinars
- Success Stories
- Developer Groups
- Trailhead Resources
- Leading Through Change with Data
- COVID-19 Data Hub
- COVID-19 Global Daily Tracker
- Global Economy Data Track
- Government Data Track
- Healthcare Data Track
- B-Well Together
- Leading Through Change
- Salesforce Care
- AppExchange Resources
- MuleSoft Resources

Don't have an account?

Browse by Topic
- View More Topics
- See All Posts
Welcome to Support!
Search for an answer or ask a question of the zone or Customer Support.
You need to sign in to do that
Sign in to start searching questions
Signup for a Developer Edition
- All Questions
- Unanswered Questions
- Unsolved Questions
- Solved Questions
- Date Posted
- Recent Activity
- Most Popular
Sign in to start a discussion
- This Question

System.QueryException: List has no rows for assignment to SObject
Hi , I'm getting this error message : System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, SetupChangeTechnologyListCheck: execution of AfterInsert caused by System.QueryException: List has no rows for assignment to SObject: : line 8, column 1
I don't understand why it doesn't find account objects, because there are alot of them in SF ? Where should I start looking for an answer to this? Many thanks already, if you could somehow help me understand this better.
trigger SetupChangeTechnologyListCheck on Setup__c (after insert, after update) { for(Setup__c s : trigger.new) { Account acc = [SELECT Name, Service_Type_List__c FROM Account WHERE RecordType.Name = 'Main Account' AND Name = :s.Main_Account__c]; UpdateMainAccountTechnologyList techList = new UpdateMainAccountTechnologyList(); techList.UpdateList(acc); } }
- December 13, 2013
The exception is because of you are not getting any record in your SOQL query..
which meet the where criteria so it's give error.
Important : Hit Kudos if this provides you with useful information and if this is what you where looking for then please mark it as a solution for other benefits. Thank You, Hitesh Patel SFDC Certified Developer & Administrator & Advanced Administrator & Sales cloud consultant My Blog:- http://mrjavascript.blogspot.in/
All Answers
Its always a best practice to check if list is not empty before doing any DML operation.
Your code could be modified tso that it doen't throw an exception:
trigger SetupChangeTechnologyListCheck on Setup__c (after insert, after update) {
for(Setup__c s : trigger.new) { list<Account> accountList = [SELECT Name, Service_Type_List__c FROM Account WHERE RecordType.Name = 'Main Account' AND Name = :s.Main_Account__c]; Account acc = (accountList != null && accountList.size()>1) ? (accountList[0] : null; if (acc != null) { UpdateMainAccountTechnologyList techList = new UpdateMainAccountTechnologyList(); techList.UpdateList(acc); } } }

- April 25, 2014
You need to sign in to do that.
Select a category.

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];
Sakthivel Madesh
3x Salesforce MVP | Platform Champion | 20x 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, meet the 2023 salesforce mvp hall of fame..., free salesforce certification days webinars – march 2023, build your chrome extensions using lwc (lwr), kapil batra – salesforce trailblazer talks, winter 22 – salesforce certification maintenance exam deadline..., spring 23 – return characters in a string..., spring 23 – track field history for activities..., free salesforce certification days webinars – december 2022, mohit agarwal – salesforce trailblazer talks, salesforce – free weekend learning from pluralsight –..., leave a comment cancel reply.
Save my name, email, and website in this browser for the next time I comment.
CAPTCHA Code *
We only have what we give
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.
Post navigation
Previous post.

IMAGES
VIDEO
COMMENTS
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:
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 Mar 2, 2015 at 18:33
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!
Some examples include: cookies used to analyze site traffic, cookies used for market research, and cookies used to display advertising that is not directed to a particular individual. Cookies Details
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...
Just try the below code public List distributionIDs {get;set;} distributionIds= [select Id from Distribution_List__c where Business_Partner__c=:relatedAccountId AND Start_Date__c today AND Status__c='Active'].Id; distItemLst= [select id from Distribution_List_Item__c where Distribution_List__c in :distributionIds]; …
Its always a best practice to check if list is not empty before doing any DML operation. Your code could be modified tso that it doen't throw an exception: trigger SetupChangeTechnologyListCheck on Setup__c (after insert, after update) { for (Setup__c s : trigger.new) {
I have a method in Visualforce Controller where I am saving the query result in a list. Here is my list. listApexJob = [SELECT Id, Status, JobItemsProcessed, TotalJobItems, NumberOfErrors FROM AsyncApexJob WHERE ID =: batchProcessId ]; How to remove the error "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.
(Note; the list of Objects are in Alpha order, scroll down to the letter "i") 8) Click Edit. 9) Go to the section "Field Permissions." 10) Look for boxes that are unchecked. *(note; ignore boxes that are greyed out, or that cannot be checked.) 11) If you see a box that is unchecked, check both Read Access and Edit Access.
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!
System.Query Exception: List has no rows for assignment to s-object? How to resolve it? Avnish Yadav replied 4 years, 5 months ago 4 Members ... Deploying LWC OSS Apps to Heroku With and Without Express API Server | Salesforce Developer Guide. Blog in Others, Salesforce. Heroku is a platform-as-a-service offering that enables developers to ...
Salesforce: List has no rows for assignment to SObject - Test ClassHelpful? Please support me on Patreon: https://www.patreon.com/roelvandepaarWith thanks &...