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.

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

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

Points to remember about Null Coalescing Operator

list has no rows for assignment to sobject salesforce 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.

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

Child to Parent communication using LWC Events | LWC Tutorial | Lightning Events in LWC

Feed Subscribe

' border=

Featured post

Sfdx deploy tool - easily deploy metadata using sfdx cli.

list has no rows for assignment to sobject salesforce 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.

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

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. Salesforce: Getting List has no rows for assignment to SObject error (4

    list has no rows for assignment to sobject salesforce apex

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

    list has no rows for assignment to sobject salesforce apex

  3. apex

    list has no rows for assignment to sobject salesforce apex

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

    list has no rows for assignment to sobject salesforce apex

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

    list has no rows for assignment to sobject salesforce apex

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

    list has no rows for assignment to sobject salesforce apex

VIDEO

  1. Apex Exercises

  2. Asychronous Apex

  3. Salesforce Platform dev 1 Apex Introduction 2

  4. Apex Basics & Database

  5. Sales Cloud: Lead Assignment Rule

  6. Use sObjects

COMMENTS

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

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

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

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

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

  6. apex

    System.QueryException: List has no rows for assignment to SObject on test class 0 Test Class Fail: Batch Class: System.QueryException: List has no rows for assignment to SObject

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

    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.

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

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

    クエリで何も行が返されないとエラー「List has no rows for assignment to SObject (sObject に割り当てる行がリストにありません)」が発生します。 解決策 通常、SELECT は配列/リストを返しますが、これらのステートメントは 1 行のみが返されることを想定した簡略構文 ...

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

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

    Unofficial Salesforce Developer Subreddit. Skip to main content. ... If it doesn't, you will get the 'List has no rows for assignment to SObject' exception again. ... Apex will give you the single record if it can find one. Your for loop does nothing except make me question why.

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

    Ask questions, find answers and collaborate at work with Stack Overflow for Teams. Explore Teams Create a free Team

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

    The error "List has no rows for assignment to SObject" occurs when a query doesn't return any rows. The error 'List has no rows for assignment to SObject'...

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