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.

SFDC Stop

SFDC Stop - Always the latest about Salesforce

Full tutorial series with videos, free apps, live sessions, salesforce consulting and much more..

  • _Platform Event Toast
  • _HTTP Callout Framework
  • _SFDX Deploy Tool
  • _SObject Convertor
  • Live Sessions
  • _TDX18GG - Salesforce UI API
  • _TDX18GG - Lightning Testing Service
  • _DF17GG - Lightning Data Service
  • Tutorial Series
  • _JavaScript Tutorial Series
  • _Salesforce LWC Tutorial Series | ToDo App Project
  • _Salesforce Integration Tutorial Series
  • _Salesforce Lightning Events Tutorial Series
  • _Salesforce Lightning Tutorial Series
  • Discussions
  • _Salesforce Development
  • _Ideas for upcoming posts
  • Become an Author

Monday 22 January 2024

Solution for "system.queryexception: list has no rows for assignment to sobject" - null coalescing operator () | spring'24 release.

list has no rows for assignment to sobject in apex

Points to remember about Null Coalescing Operator

list has no rows for assignment to sobject in apex

About Rahul Malhotra Rahul Malhotra is currently working as an Application Engineer at Google . He has delivered various live technical sessions at International and National Salesforce Conferences including TrailheaDX India 2019, Dreamforce 2018, IndiaDreamin 2018, Jaipur Developer Fest 2018 as well as other global gatherings of Salesforce. Connect with him on Connections App . Username: rahulmalhotra

No comments:

Post a comment, mastering lightning datatable in salesforce lwc.

Mastering Lightning Datatable in Salesforce LWC

Learn how to implement lightning datatable in LWC from scratch. Implement all features from basic to advanced level.

Connections - Store all your professional contacts without auto sync with any other apps

Connections - Store all your professional contacts without auto sync with any other apps

Connections helps users to store all their business/professional contacts. None of the contacts are automatically synced with any other applications like: whatsapp, installed on the device.

Connect with me on connections using my username: rahulmalhotra

Recognized by Apex Hours as Top Salesforce Blog

Recognized by Apex Hours as Top Salesforce Blog

$50 OFF with LIFETIME ACCESS. Complete Salesforce Platform & Lightning Experience Training Pack

$50 OFF with LIFETIME ACCESS. Complete Salesforce Platform & Lightning Experience Training Pack

LWC Training

LWC Training

Competitive Programming Solutions

Competitive Programming Solutions

Subscribe for free tutorials

  • @rahulcoder

Custom validation in Lightning Web Component | Understanding Regular Expressions (Regex)

  • How to solve UNABLE_TO_LOCK_ROW, unable to obtain exclusive access to this record or N records? Hello Trailblazers, Recently, I faced this issue in one of the projects I was working on. The issue was  UNABLE_TO_LOCK_ROW, unable to obtai...

Feed Subscribe

' border=

Featured post

Sfdx deploy tool - easily deploy metadata using sfdx cli.

list has no rows for assignment to sobject in apex

Report Abuse

Blog archive.

  • Affiliate Disclaimer
  • Privacy Policy
  • Contribute to SFDC Stop | Become an Author
  • What do you want to see next on SFDC Stop ?

Total Pageviews

Recent comments.

  • Marketing Cloud

Experiences

Access Trailhead, your Trailblazer profile, community, learning, original series, events, support, and more.

Search Tips:

  • Please consider misspellings
  • Try different search keywords

SObject Class

SObject methods are all instance methods: they are called by and operate on an sObject instance such as an account or contact. The following are the instance methods for sObjects.

For more information on sObjects, see Working with sObjects .

SObject Methods

The following are methods for SObject . All are instance methods.

  • addError(errorMsg) Marks a trigger record with a custom error message and prevents any DML operation from occurring.
  • addError(errorMsg, escape) Marks a trigger record with a custom error message, specifies if the error message should be escaped, and prevents any DML operation from occurring.
  • addError(exceptionError) Marks a trigger record with a custom error message and prevents any DML operation from occurring.
  • addError(exceptionError, escape) Marks a trigger record with a custom exception error message, specifies whether or not the exception error message should be escaped, and prevents any DML operation from occurring.
  • addError(errorMsg) Places the specified error message on a trigger record field in the Salesforce user interface and prevents any DML operation from occurring.
  • addError(errorMsg, escape) Places the specified error message, which can be escaped or unescaped, on a trigger record field in the Salesforce user interface, and prevents any DML operation from occurring.
  • addError(fieldName, errorMsg) Dynamically add errors to fields of an SObject associated with the specified field name.
  • addError(fieldToken, errorMsg) Dynamically add errors to an SObject instance associated with the specified field.
  • addError(fieldName, errorMsg, escape) Dynamically add errors to fields of an SObject associated with the specified field name.
  • addError(fieldToken, errorMsg, escape) Dynamically add errors to an SObject instance associated with the specified field.
  • clear() Clears all field values
  • clone(preserveId, isDeepClone, preserveReadonlyTimestamps, preserveAutonumber) Creates a copy of the SObject record.
  • get(fieldName) Returns the value for the field specified by fieldName , such as AccountNumber .
  • get(field) Returns the value for the field specified by the field token Schema. sObjectField , such as, Schema.Account.AccountNumber .
  • getCloneSourceId() Returns the ID of the entity from which an object was cloned. You can use it for objects cloned through the Salesforce user interface. You can also use it for objects created using the System.SObject. clone(preserveId, isDeepClone, preserveReadonlyTimestamps, preserveAutonumber) method, provided that the preserveId parameter wasn’t used or was set to false . The getCloneSourceId() method can only be used within the transaction where the entity is cloned, as clone information doesn’t persist in subsequent transactions.
  • getErrors() Returns a list of Database.Error objects for an SObject instance. If the SObject has no errors, an empty list is returned.
  • getOptions() Returns the database.DMLOptions object for the SObject.
  • getPopulatedFieldsAsMap() Returns a map of populated field names and their corresponding values. The map contains only the fields that have been populated in memory for the SObject instance.
  • getSObject(fieldName) Returns the value for the specified field. This method is primarily used with dynamic DML to access values for external IDs.
  • getSObject(field) Returns the value for the field specified by the field token Schema. sObjectField , such as, Schema.MyObj.MyExternalId . This method is primarily used with dynamic DML to access values for external IDs.
  • getSObjects(fieldName) Returns the values for the specified field. This method is primarily used with dynamic DML to access values for associated objects, such as child relationships.
  • getSObjects(fieldName) Returns the value for the field specified by the field token Schema. fieldName , such as, Schema.Account.Contact . This method is primarily used with dynamic DML to access values for associated objects, such as child relationships.
  • getSObjectType() Returns the token for this SObject. This method is primarily used with describe information.
  • getQuickActionName() Retrieves the name of a quick action associated with this SObject. Typically used in triggers.
  • hasErrors() Returns true if an SObject instance has associated errors. The error message can be associated to the SObject instance by using SObject.addError() , validation rules, or by other means.
  • isClone() Returns true if an entity is cloned from something, even if the entity hasn’t been saved. The method can only be used within the transaction where the entity is cloned, as clone information doesn’t persist in subsequent transactions.
  • isSet(fieldName) Returns information about the queried sObject field. Returns true if the sObject field is populated, either by direct assignment or by inclusion in a SOQL query. Returns false if the sObject field isn’t set. If an invalid field is specified, an SObjectException is thrown.
  • isSet(field) Returns information about the queried sObject field. Returns true if the sObject field is populated, either by direct assignment or by inclusion in a SOQL query. Returns false if the sObject field isn’t set. If an invalid field is specified, an SObjectException is thrown.
  • put(fieldName, value) Sets the value for the specified field and returns the previous value for the field.
  • put(field, value) Sets the value for the field specified by the field token Schema. sObjectField , such as, Schema.Account.AccountNumber and returns the previous value for the field.
  • putSObject(fieldName, value) Sets the value for the specified field. This method is primarily used with dynamic DML for setting external IDs. The method returns the previous value of the field.
  • putSObject(fieldName, value) Sets the value for the field specified by the token Schema.SObjectType . This method is primarily used with dynamic DML for setting external IDs. The method returns the previous value of the field.
  • recalculateFormulas() Deprecated as of API version 57.0. Use the recalculateFormulas() method in the System.Formula class instead.
  • setOptions(DMLOptions) Sets the DMLOptions object for the SObject.

addError(errorMsg)

public Void addError( String errorMsg)

The error message to mark the record with.

Return Value

When used on Trigger. new in insert and update triggers, and on Trigger.old in delete triggers, the error message is displayed in the application interface.

See Triggers and Trigger Exceptions .

This method escapes any HTML markup in the specified error message. The escaped characters are: \n , < , > , & , " , \ , \u2028 , \u2029 , and \u00a9 . As a result, HTML markup is not rendered; instead, it is displayed as text in the Salesforce user interface.

When used in Visualforce controllers, the generated message is added to the collection of errors for the page. For more information, see Validation Rules and Standard Controllers in the Visualforce Developer's Guide .

addError(errorMsg, escape)

public Void addError( String errorMsg, Boolean escape)

Indicates whether any HTML markup in the custom error message should be escaped ( true ) or not ( false ). This parameter is ignored in both Lightning Experience and the Salesforce mobile app, and the HTML is always escaped. The escape parameter only applies in Salesforce Classic.

The escaped characters are: \n , < , > , & , " , \ , \u2028 , \u2029 , and \u00a9 . As a result, HTML markup is not rendered; instead, it is displayed as text in the Salesforce user interface.

Be cautious if you specify false for the escape argument. Unescaped strings displayed in the Salesforce user interface can represent a vulnerability in the system because these strings might contain harmful code. If you want to include HTML markup in the error message, call this method with a false escape argument. Make sure that you escape any dynamic content, such as input field values. Otherwise, specify true for the escape argument or call addError( String errorMsg ) instead.

addError(exceptionError)

public Void addError(Exception exceptionError)

An Exception object or a custom exception object that contains the error message to mark the record with.

addError(exceptionError, escape)

public Void addError(Exception exceptionError, Boolean escape)

Be cautious if you specify false for the escape argument. Unescaped strings displayed in the Salesforce user interface can represent a vulnerability in the system because these strings might contain harmful code. If you want to include HTML markup in the error message, call this method with a false escape argument. Make sure that you escape any dynamic content, such as input field values. Otherwise, specify true for the escape argument or call addError(Exception e) instead.

  • When used on Trigger. new in before insert and before update triggers, and on Trigger.old in before delete triggers, the error appears in the application interface.
  • When used in Visualforce controllers, if there is an inputField component bound to field, the message is attached to the component. For more information, see Validation Rules and Standard Controllers in the Visualforce Developer's Guide .
  • This method is highly specialized because the field identifier is not actually the invoking object—the sObject record is the invoker. The field is simply used to identify the field that should be used to display the error.

Be cautious if you specify false for the escape argument. Unescaped strings displayed in the Salesforce user interface can represent a vulnerability in the system because these strings might contain harmful code. If you want to include HTML markup in the error message, call this method with a false escape argument. Make sure that you escape any dynamic content, such as input field values. Otherwise, specify true for the escape argument or call field .addError( String errorMsg ) instead.

addError(fieldName, errorMsg)

public void addError( String fieldName, String errorMsg)

If the field name is an empty string or null, the error is associated with the SObject and not with a specific field.

addError(fieldToken, errorMsg)

public void addError(Schema.SObjectField fieldToken, String errorMsg

Use this method to add errors to the specified field token of a standard or custom object. If fieldToken is null, the error is associated with the SObject and not with a specific field.

addError(fieldName, errorMsg, escape)

public void addError( String fieldName, String errorMsg, Boolean escape)

  • The escape parameter cannot be disabled in Lightning Experience and in the Salesforce mobile app, and will be ignored.
  • Be cautious if you specify false for the escape argument. Unescaped strings displayed in the Salesforce user interface can represent a vulnerability in the system because these strings might contain harmful code. If you want to include HTML markup in the error message, call this method with a false escape argument. Make sure that you escape any dynamic content, such as input field values. Otherwise, specify true for the escape argument or call addError( String fieldName, String errorMsg) instead.

addError(fieldToken, errorMsg, escape)

public void addError(Schema.SObjectField fieldToken, String errorMsg, Boolean escape)

  • Be cautious if you specify false for the escape argument. Unescaped strings displayed in the Salesforce user interface can represent a vulnerability in the system because these strings might contain harmful code. If you want to include HTML markup in the error message, call this method with a false escape argument. Make sure that you escape any dynamic content, such as input field values. Otherwise, specify true for the escape argument or call addError(Schema.SObjectField fieldToken, String errorMsg) instead.

public Void clear()

clone(preserveId, isDeepClone, preserveReadonlyTimestamps, preserveAutonumber)

public SObject clone( Boolean preserveId, Boolean isDeepClone, Boolean preserveReadonlyTimestamps, Boolean preserveAutonumber)

  • If set to true , the method creates a full copy of the SObject. All fields on the SObject are duplicated in memory, including relationship fields. Consequently, if you change a field on the cloned SObject, the original SObject isn’t affected.
  • If set to false , the method performs a shallow copy of the SObject fields. All copied relationship fields reference the original SObjects. Consequently, if you change a relationship field on the cloned SObject, the corresponding field on the original SObject is also affected, and vice versa. The default is false .

Audit field values won’t be persisted to the database via DML on the cloned SObject instance.

Type: SObject (of the same type)

For Apex saved using Salesforce API version 22.0 or earlier, the default value for the preserveId argument is true , that is, the ID is preserved.

get(fieldName)

public Object get( String fieldName)

Type: Object

For more information, see Dynamic SOQL .

Versioned Behavior Changes

In API version 34.0 and later, you must include the namespace name to retrieve a field from a field Map using this method. For example, to get the account__c field in the MyNamespace namespace from a fields field Map, use: fields.get(‘MyNamespace__account__c’) .

public Object get(Schema.sObjectField field)

Field tokens aren't available for person accounts. If you access Schema.Account. fieldname , you get an exception error. Instead, specify the field name as a string.

getCloneSourceId()

public Id getCloneSourceId()

If A is cloned to B, B is cloned to C, and C is cloned to D, then B, C, and D all point back to A as their clone source.

getErrors()

public List<Database.Error> getErrors()

Type: List < Database.Error >

getOptions()

public Database.DMLOptions getOptions()

Type: Database.DMLOptions

getPopulatedFieldsAsMap()

public Map< String , Object > getPopulatedFieldsAsMap()

Type: Map<String,Object>

A map of field names and their corresponding values.

  • The field has been queried by a SOQL statement.
  • The field has been explicitly set before the call to the getPopulatedFieldsAsMap() method.

The following example iterates over the map returned by the getPopulatedFieldsAsMap() method after a SOQL query.

This example iterates over the map returned by the getPopulatedFieldsAsMap() method after fields on the SObject are explicitly set.

The following example shows how to use the getPopulatedFieldsAsMap() method with related objects.

In API version 39.0 and later, getPopulatedFieldsAsMap returns all values set on the SObject, even if values were set after the record was queried. This behavior is dependent on the version of the apex class calling this method and not on the version of the class that generated the SObject. If you query an SObject at API version 20.0, and then call this method in a class with API version 40.0, you will get the full set of fields.

getSObject(fieldName)

public SObject getSObject( String fieldName)

Type: SObject

getSObject(field)

public SObject getSObject(Schema.SObjectField field)

If the method references polymorphic fields, a Name object is returned. Use the TYPEOF clause in the SOQL SELECT statement to directly get results that depend on the runtime object type referenced by the polymorphic field. See Working with Polymorphic Relationships in SOQL Queries .

getSObjects(fieldName)

public SObject[] getSObjects( String fieldName)

Type: SObject []

For more information, see Dynamic DML .

public SObject[] getSObjects(Schema.SObjectType fieldName)

getSObjectType()

public Schema.SObjectType getSObjectType()

Type: Schema.SObjectType

For more information, see apex_dynamic_describe_objects_understanding.

getQuickActionName()

public String getQuickActionName()

Type: String

hasErrors()

public Boolean hasErrors()

Type: Boolean

public Boolean isClone()

isSet(fieldName)

public Boolean isSet( String fieldName)

The isSet method doesn’t check if a field is accessible to a specific user via org permissions or other specialized access permissions.

isSet(field)

public Boolean isSet(Schema.SObjectField field)

put(fieldName, value)

public Object put( String fieldName, Object value)

put(field, value)

public Object put(Schema.SObjectField field, Object value)

putSObject(fieldName, value)

public SObject putSObject( String fieldName, SObject value)

public SObject putSObject(Schema.SObjectType fieldName, SObject value)

recalculateFormulas()

public Void recalculateFormulas()

This method doesn’t recalculate cross-object formulas. If you call this method on objects that have both cross-object and non-cross-object formula fields, only the non-cross-object formula fields are recalculated.

Each recalculateFormulas call counts against the SOQL query limits. See Execution Governors and Limits .

  • recalculateFormulas(sobjects)
  • What Is a Cross-Object Formula?

setOptions(DMLOptions)

public Void setOptions(database.DMLOptions DMLOptions)

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 with  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. Or, you can create a group, grant access to the group, and add users to that group.
  • Make sure to deactivate and reactivate the Document Template
  •  If there are custom fields in the Content Version object, marked as required, the error occurs. The managed package code will not update custom fields and they need to be marked required only at the Page Layout level.
  • For DOCX Templates, the ContentVersionId will be set for the affected Document Template. Make sure this record is shared with the Docgen Document Template Library to avoid any errors.
  •  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.

Company Logo

Cookie Consent Manager

General information, required cookies, functional cookies, advertising cookies.

We use three kinds of cookies on our websites: required, functional, and advertising. You can choose whether functional and advertising cookies apply. Click on the different cookie categories to find out more about each category and to change the default settings. Privacy Statement

Required cookies are necessary for basic website functionality. Some examples include: session cookies needed to transmit the website, authentication cookies, and security cookies.

Functional cookies enhance functions, performance, and services on the website. 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.

Advertising cookies track activity across websites in order to understand a viewer’s interests, and direct them specific marketing. Some examples include: cookies used for remarketing, or interest-based advertising.

Cookie List

IMAGES

  1. apex

    list has no rows for assignment to sobject in apex

  2. apex

    list has no rows for assignment to sobject in apex

  3. apex

    list has no rows for assignment to sobject in apex

  4. apex

    list has no rows for assignment to sobject in apex

  5. apex

    list has no rows for assignment to sobject in apex

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

    list has no rows for assignment to sobject in apex

VIDEO

  1. Oracle APEX

  2. Unbalanced Assignment Problem

  3. Apex Basics & Database

  4. How to delete records using Apex

  5. How to update records using Apex

  6. APEX_ITEM :DATE_POPUP

COMMENTS

  1. apex

    List has no rows for assignment to SObject - Test Class Ask Question Asked 7 years, 10 months ago Modified 7 years, 10 months ago Viewed 19k times 4 Another one of these, I know. I have been looking at similar errors for the last few hours with no luck.

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

    Apex error 'List has no rows for assignment to SObject' The following query is not returning any number of records: " [SELECT Id FROM Account WHERE Id = :Trigger.new [0].Account__c]" The error "List has no rows for assignment to SObject" occurs when query doesn't return any rows.

  3. apex

    System.QueryException: List has no rows for assignment to SObject Error shown in this line: opportunities = [SELECT Name,Amount,StageName FROM opportunity WHERE Id = :recId AND StageName NOT IN ('Closed Lost', 'Closed Won')]; apex visualforce Share Improve this question Follow edited Sep 3, 2020 at 19:06 Caconde 4,333 7 35 32

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

    Apex error 'List has no rows for assignment to SObject' The following query is not returning any number of records: " [SELECT Id FROM Account WHERE Id = :Trigger.new [0].Account__c]" While a SELECT normally returns an array/list, these statements are using the shorthand syntax that assumes only one row is returned.

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

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

    The error 'List has no rows for assignment to SObject' occurs when an invalid quote process ID exists on the Quote's Quote Process ID field. This field is meant to be populated by automation. This issue can also occur when the user attempts to reconfigure a Primary Quote without Read access to the associated Opportunity.

  7. Solution for "System.QueryException: List has no rows for assignment to

    The query which we're performing is returning a list which has no rows (no records) to assign to the contactRecord variable which is of type Contact sObject. So, we can say "List has no rows for assignment to SObject".

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

  9. Apex エラー「List has no rows for assignment to SObject (sObject に割り当てる行が

    Apex エラー「List has no rows for assignment to SObject (sObject に割り当てる行がリストにありません)」 公開日: Oct 13, 2022 次のクエリは、レコードを 1 件も返しません。 : " [SELECT Id FROM Account WHERE Id = :Trigger.new [0].Account__c]" クエリで何も行が返されないとエラー「List has no rows for assignment to SObject (sObject に割り当てる行がリストにありません)」が発生します。

  10. SObject Class

    If the SObject has no errors, an empty list is returned. getOptions() Returns the database.DMLOptions object for the SObject. getPopulatedFieldsAsMap() Returns a map of populated field names and their corresponding values. The map contains only the fields that have been populated in memory for the SObject instance. getSObject(fieldName)

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

    Can somebody explain the error 'System.QueryException: List has no rows for assignment to SObject'? Ask Question Asked 1 year, 3 months ago Modified 1 year, 3 months ago Viewed 2k times 0 everyone. Im new to apex, I was trying for code coverage of atleast 75% on my batch apex code through test class.

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

    Resolution 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 with 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. testing

    Error in apex test logs: common.apex.runtime.impl.ExecutionException: List has no rows for assignment to SObject" Ask Question Asked 4 years, 11 months ago Modified 4 years, 10 months ago Viewed 1k times 0 Here is what i tried.