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.

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

  • Featured on Meta
  • Announcing a change to the data-dump process
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...

Hot Network Questions

  • Book about a spaceship that crashed under the surface of a planet
  • If every definable class admits a group structure, must global choice hold?
  • Is there a way to render someone braindead while leaving the organs and body fully intact?
  • Publishing a paper written in your free time as an unaffiliated author when you are affiliated
  • Dividing shape into 2 congruent pieces
  • Why did Kamala Harris once describe her own appearance at the start of an important meeting?
  • How do I drop a database which has brackets in its name?
  • Tale of two servers. What could be limiting queries to running on two cores? MDOP set to 16
  • Is there any point to the copyright notice in 0BSD?
  • What are applicable skills and abilities for dealing with paperwork, administration and law in 5e?
  • When does HDMI TMDS apply inversion on first 8 encoded bits?
  • Natural person / is it idiomatic?
  • When labeling, "Wrap on character" drops the wrap character
  • Take screenshot of rendered HTML from Linux without GUI
  • Why "praemiīs mē dōnant" and not "praemia mihi donant"?
  • Do we ever see the dangers of violating the Prime Directive?
  • What factors need to be taken into account in assessing the meaning of "the will of God" in Mark 3:35?
  • How can dragons breathe in space?
  • A hat puzzle question—how to prove the standard solution is optimal?
  • Swale puddles/floods before driveway - looking for solution
  • What's the frequency level of 時々?
  • Securing Transactional Email: User Input Escaping for a email subject
  • My iterative FFT is slower than my recursive FFT
  • Why do some license agreements ask for the signee's date of birth?

list has no rows for assignment to sobject limit 1

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

NEED HELP: List has more than 1 row for assignment to SObject

Need help on why the list has more than 1 row for assignment

Here's the code:

if(Trigger.isBefore && Trigger.isInsert){

for(City_Census__c a: Trigger.new )

List<Group> queue = [SELECT Name FROM Group WHERE Type = 'Queue'];

List<String> qNames = new List<String>();

for(Group s:queue)

qNames.add( s.Name );

System.debug(qNames);

ID cId = [SELECT Queue.Id FROM queuesobject WHERE queue.name IN:qNames].Queue.Id;

String[] cities = a.City__c.split(';');

for(Integer i=0;i<cities.size();i++){

if(a.City__c == cities[i])

a.OwnerId = cId;

if(a.Auto_Approve__c==true)

a.Approval_Status__c = 'Approved';

//createResident.addResident ( Trigger.new );

a.Approval_Status__c = 'For Approval';

Thank you so much for the help

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.

Error in apex test logs: common.apex.runtime.impl.ExecutionException: List has no rows for assignment to SObject"

Here is what i tried. I think the problem is somewhere in the test class when i create the apex test controller and i want to link the record of the controller to the solution that i created in the test class.

This is the error that i found in logs: "common.apex.runtime.impl.ExecutionException: List has no rows for assignment to SObject"|0x4888dd3c

Here is my test class

apex test class:

  • visualforce

cUser's user avatar

Solution id is different from the one that i inserted in the test class. I inserted a dummy value (eq 'test') on a field like Currency. After that i selected from the db based on Currency instead of id.

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

  • Featured on Meta
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
  • Announcing a change to the data-dump process

Hot Network Questions

  • Is it possible to express any multi-qubit quantum unitary operation as a rotation about a specific unit vector?
  • "Nam sī qua alia urbs, est īnsalūbris Rōma."
  • Relationship between Pythagorean Triples and double/half angles
  • How can I prevent my fountain's water from turning green?
  • Does this follow from Everett's Many-Worlds?
  • What is the maximum number of real roots in the interval (0,1) of a monic polynomial with integer coefficients and has degree 2022.
  • Explain This Star Battle Clue
  • Publishing a paper written in your free time as an unaffiliated author when you are affiliated
  • When we say "roll out" a product, do we mean like a carpet or like a car?
  • Drawing line defined by start and end points within attribute table in QGIS
  • Why exactly do we need the learning rate in gradient descent?
  • Natural person / is it idiomatic?
  • What programming language was used in Dijkstra's response to Frank Rubin's article about "Go To Statement Considered Harmful"
  • How do I drop a database which has brackets in its name?
  • Has any US president ever endorsed Trump for US presidency?
  • Can modern civilization maintain itself under an Earth constantly bombarded with lightning?
  • How to estimate temperature based on known points in a map?
  • What factors need to be taken into account in assessing the meaning of "the will of God" in Mark 3:35?
  • If every definable class admits a group structure, must global choice hold?
  • Help me understand if this BJT are in saturation, cut-off mode or none
  • Is the text of speeches by foreign leaders (given to the US Congress) entered into the Congressional Record?
  • Bike post slips down
  • How to address imbalanced work assignments to new boss?
  • Tale of two servers. What could be limiting queries to running on two cores? MDOP set to 16

list has no rows for assignment to sobject limit 1

IMAGES

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

    list has no rows for assignment to sobject limit 1

  2. Salesforce: List has no rows for assignment to SObject in a test class

    list has no rows for assignment to sobject limit 1

  3. System.QueryException: List has no rows for assignment to SObject for Object created in test case

    list has no rows for assignment to sobject limit 1

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

    list has no rows for assignment to sobject limit 1

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

    list has no rows for assignment to sobject limit 1

  6. Salesforce: List has no rows for assignment to SObject

    list has no rows for assignment to sobject limit 1

VIDEO

  1. CLASS 12 Chapter 2 Relation or a Table#ar3noor

  2. Across the APIs: Salesforce REST SObject Describe and Retrieve

  3. Salesforce: Error: Invalid field Job_Application__r for SObject Position__c (2 Solutions!!)

  4. Salesforce: SObject row was retrieved via SOQL without querying the requested field (4 Solutions!!)

  5. Salesforce: Get a deleted record using SObject Rows returns "The requested resource does not exist"

  6. Salesforce: System.QueryException: List has no rows for assignment to SObject (3 Solutions!!)

COMMENTS

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

  2. List has no rows for assignment to SObject

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

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

    Meaning query will still return 0 rows. What were you trying to do? Maybe just removing that part of condition will help although this list can grow very fast. You might want to put a LIMIT statement in the query or read about StandardSetController and pagination.

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

  7. execution of BeforeInsert caused by: System.QueryException: List has no

    But as list is empty, hence you see an exception List has no rows for assignment to SObject. I am not aware of full use case, but you can try shifting your context to AfterInsert. BTW, why to just query Id again, if you already have an Id from the trigger.

  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. 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. If the SOQL query finds no records, it always returns ...

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

  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 ... Yes you have to have limit 1 to the query but make sure you have records coming out of that query first. Reply reply [deleted] • ...

  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. To enable users to access the files in the Document Template Library, you must add them as members.

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

    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.. Visit Stack Exchange

  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. How to fix "System.QueryException: List has more than 1 row for

    List has no rows for assignment to SObject when the value is returned. 3 'List has no rows for assignment to SObject' Mystery. 1. Insert and then select in VF controller giving List has no rows for assignment to SObject. Hot Network Questions Professor Previously wrote letter, and now he's not responding to my emails

  16. List has more than 1 row for assignment to SObject

    List has more than 1 row for assignment to SObject. if I limit the query with one record it's working, but I wanted to get the list of records. public static List<Account> AccountsRequiringDebtCase() {. Integer creditTermDate30 = 2; Integer creditTermDate35 = 7; Integer creditTermDate45 = 17; List<Account> accList = new List<Account>();

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

  18. NEED HELP: List has more than 1 row for assignment to SObject

    List<Group> queue = [SELECT Name FROM Group WHERE Type = 'Queue']; This SOQL query will return more than 1 record. You are then using this result to populate values in List<String> qNames. ID cId = [SELECT Queue.Id FROM queuesobject WHERE queue.name IN:qNames].Queue.Id;. Now, you are using qNames in WHERE clause to get query data from queuesobject. Since qNames has more than 1 record, the ...

  19. testing

    Here is what i tried. I think the problem is somewhere in the test class when i create the apex test controller and i want to link the record of the controller to the solution that i created in ...