+ Start a Discussion
Ertyq MrskErtyq Mrsk 

AuraEnabled Apex Class Returning Following Error: System.QueryException: List has no rows for assignment to SObject

In my following AuraEnabled class, I am trying to clone the current record displayed in my lightning component page. This lightning component implements force:hasRecordId and should insert it as new value instead of updating the current one.

But upon checking the developer console's debug logs, I always see this error:

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

What should I do to fix said error?

public with sharing class ItemsController {
    public static Item__c cloneItem(Id itemId){
        Item__c itemToClone = new Item__c();

        itemToClone = [SELECT Id, MasterField__c FROM Item__c WHERE Id =: itemId LIMIT 1];

        Item__c newCloneItem = new Item__c();
        newCloneItem = itemToClone.clone();
        newCloneItem.MasterField__c = itemToClone.MasterField__c;
        insert newCloneItem; 
        return newCloneItem;

Put a debug statement in APEX to see if itemId is getting value from lightning. If not, debug lightning component to see why it's not passing the value to the apex.
AbhishekAbhishek (Salesforce Developers) 
The exception is because you are not getting any record in your SOQL query which meets the where criteria so it gives an error. When attempting to fetch a single record from the database it is easy to run into the above exception. To avoid such exception use a try-catch box like below :

MyObject__c obj;


obj = [SELECT id FROM MyObject__c WHERE name=:previouslyDefinedVar];

} catch(System.QueryException e){

// Perform logic here


For further reference, you can check this too,


Let me know if it helps you and close your query by marking it as solved so that it can help others in the future.