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.

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

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

I'm trying to compare this very simple test designed to query a record within an actual database to other examples of this error online, only the examples I've seen are more complex than what I'm doing.

My code is here:

public class IncompleteWorkshopLogsTest {

What does this error mean? I thought it meant I needed to print the result or Systemdebug - but I'm getting the same error. Man oh man this isn't rspec. The test passed in the console but does not pass in the deployment.

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

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

System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, UPCustomTrigger: execution of AfterInsert

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

Class.UPCustomtriggerHandler.afterUprInsert: line 278, column 1 Trigger.UPCustomTrigger: line 10, column 1: []

I am getting this error but not able to figure it out. Due to this am not able to cover 5 test classes. Could anyone please clear me why am getting this error.

The issue am facing is I am not able to insert/update ICIX_V1__UP_Relationship__c records.

Controller:

The Error is at below line what mistake I made? Id InternalAccId = [SELECT Id FROM Account WHERE ICIX_V1__Internal__c = true].Id;

  • queryexception

Santhiya's user avatar

Your query:

Will throw this exception when there are no rows to assign (no record is found). The following code:

Won't protect you from this exception. To fix the problem, add a for-query loop:

As far as your unit test goes, you need to manually create the record (see Isolation of Test Data from Organization Data in Unit Tests ).

sfdcfox's user avatar

  • Hi @sfdcfox. I tried the solution which you have given. its throwing an error. on: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, UPCustomTrigger: execution of AfterInsert caused by: System.ListException: List index out of bounds: 0 –  Santhiya Commented Sep 16, 2020 at 8:38
  • and getting a new error on the same controller. I have edited my question as per my concern. –  Santhiya Commented Sep 16, 2020 at 8:39
  • @Santhiya The same mistake as before. You need to write your code to accept the possibility that there may be no records present. –  sfdcfox ♦ Commented Sep 16, 2020 at 12:59

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged unit-test queryexception ..

  • The Overflow Blog
  • From PHP to JavaScript to Kubernetes: how one backend engineer evolved over time
  • 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

  • Op Amp Feedback Resistors
  • NSum result quite different from Sum. Euler Maclaurin won‘t work!
  • Calculate the sum of numbers in a rectangle
  • Is there racial discrimination at Tbilisi airport?
  • Meaning of capacitor "× 2" symbol on data sheet schematic
  • Reduce String Length With Thread Safety & Concurrency
  • Old TV episode about a rich man and his guests trapped in his high-tech underground bunker after a nuclear disaster
  • A connections style puzzle
  • What are the limits of Terms of Service as a legal shield for a company?
  • Sticker on caption phone says that using the captions can be illegal. Why?
  • Invalid coefficients in Quantum Process Tomography of the Hadamard gate
  • Looking for an old game on Ubuntu I played when I was a kid
  • Time dilation with variable time scale
  • Where to put \pgfmathsetmacro into forest is correct and get highest efficiency?
  • How can I push back on my co-worker's changes that I disagree with?
  • Is there a rule-of-thumb for when a first-person singular verb will get a "-у" vs the more common "-ю" suffix?
  • What's the Matter?
  • Do cities usually form at the mouth of rivers or closer to the headwaters?
  • There are at least 3 versions of a quote, with 2 having different attributions. What is the original, who said it, and what does the quote mean?
  • Frequency resolution in STFT
  • Which cards use −5 V and −12 V in IBM PC compatible systems?
  • Video game where the hero gets transported to another world with his sister to aid a king in a war
  • How to ensure a BSD licensed open source project is not closed in the future?
  • Sci-fi scenario: Is it possible to detect and either broadcast over or otherwise block satellite comms to and from a geographic area that you control?

exception (400) list has no rows for assignment to sobject

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

System.QueryException: List has more than 1 row for assignment to SObject

System.QueryException: List has more than 1 row for assignment to SObject Error is in expression '{!search}' in component apex:commandButton in page simpsons_vf01_car_show: Class.Simpsons_Cl1_classCar.search: line 36, column 1

David Reed's user avatar

  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. –  Community Bot Commented Jan 4, 2022 at 19:42

Presumably the value sim is of type Car__c . You cannot assign the result of a query that returns anything other than exactly one record to a value whose type is an SObject. In particular, this does not make sense when you're performing a search query with a LIMIT 20 clause.

You should type your variable as a List<Car__c> .

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

  • The Overflow Blog
  • From PHP to JavaScript to Kubernetes: how one backend engineer evolved over time
  • 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...

Hot Network Questions

  • Winner of block reward command
  • Should I GFCI-protect a bathroom light and fan?
  • Self-Contained Explanation of the Fluctuation-Dissipation Theorem?
  • Did US troops insist on segregation in British pubs?
  • Frequency resolution in STFT
  • Difference between 頁 and ページ
  • How can I push back on my co-worker's changes that I disagree with?
  • Rashi's opinion on the child of a gentile father
  • Meaning of capacitor "× 2" symbol on data sheet schematic
  • Implement service registry servers with load balancing strategies
  • There are at least 3 versions of a quote, with 2 having different attributions. What is the original, who said it, and what does the quote mean?
  • Is it possible to do physics without mathematics?
  • Copper bonding jumper around new whole-house water filter system
  • Degree of a cyclotomic polynomial
  • Is there a rule-of-thumb for when a first-person singular verb will get a "-у" vs the more common "-ю" suffix?
  • Sticker on caption phone says that using the captions can be illegal. Why?
  • How to determine if a set is countable or uncountable?
  • Miracle Miracle Octad Generator Generator
  • How do you hide an investigation of alien ruins on the moon during Apollo 11?
  • Virtualbox stopped working (Package has no installation candidate)
  • Op Amp Feedback Resistors
  • Why are the titles of certain types of works italicized?
  • Vector of integers such that almost all dot products are positive
  • Clarification on proof of the algebraic completeness of nimbers

exception (400) list has no rows for assignment to sobject

IMAGES

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

    exception (400) list has no rows for assignment to sobject

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

    exception (400) list has no rows for assignment to sobject

  3. Salesforce: List has No Rows for Assignment to SObject: Error

    exception (400) list has no rows for assignment to sobject

  4. Salesforce: System.QueryException: List has no rows for assignment to

    exception (400) list has no rows for assignment to sobject

  5. Salesforce: Visualforce System.QueryException: List has no rows for

    exception (400) list has no rows for assignment to sobject

  6. Salesforce: Test Class

    exception (400) list has no rows for assignment to sobject

COMMENTS

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

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

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

  4. List has no rows for assignment to SObject

    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.

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

    This issue can also occur when the user attempts to reconfigure a Primary Quote without Read access to the associated Opportunity. 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.

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

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

  8. CLM-Document Generation Error- "List has no rows for assignment to

    Open the active template in the Document Template tab (NOT the Vlocity 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.

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

  10. 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. ... Having one record gets you 100% coverage and doesn't throw exceptions or have multiple exits. Again, not a huge deal in this particular case but good habits are worth a lot more than lazy, thoughtless ones.

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

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

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

  14. DocuSign custom button error, "List has no rows for assignment to SObject"

    If the SOQL query returns no results (an empty list), then there is no record at index 0 (the first item in the list), and result is an exception. Now, none of your JS code above does any actual SOQL, so the only thing I can think of is that somewhere the Docusign code is searching for a record and isn't able to find anything.

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

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

    Your issue with both your trigger and your test class are because you've hardcoded a userId into your code. This is a very poor practice. You're much safer to select a profile to use for the user who will have the correct permissions to perform the operation.

  17. Salesforce Error: List has no rows for assignment to SObject

    Error: [User Profile] does not have permission to... iContact Sent Message. Error: List has no rows for assignment to SObject. Error: User unable to update ... Permission Denied. Please check your Field Level Security settings. These errors can occur for iContact for Salesforce Users that do not have Read Access for iContact Custom Fields.

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

    First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, UPCustomTrigger: execution of AfterInsert caused by: System.QueryException: List has no rows for assignment to SObject Class.UPCustomtriggerHandler.afterUprInsert: line 278, column 1 Trigger.UPCustomTrigger: line 10, column 1: []

  19. System.QueryException: List has more than 1 row for assignment to SObject

    Presumably the value sim is of type Car__c.You cannot assign the result of a query that returns anything other than exactly one record to a value whose type is an SObject. In particular, this does not make sense when you're performing a search query with a LIMIT 20 clause.. You should type your variable as a List<Car__c>.