function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Andrew EchevarriaAndrew Echevarria 

SOQL WHERE Query using value from CSV file

I'm writing an Apex class that reads a CSV spreadsheet and inserts object records accordingly. I can confirm my program can read all the fields and create insert new records with the respective fields, but I'm having a problem when I try SOQL query an Object__c record using a value from the CSV file. I recieve an error telling me "caused by: System.QueryException: List has no rows for assignment to SObject". 
String field = csvRow[4]);  
Object__c  obj = [Select Id, Name from Object__c where Name =: field];

So it's not finding the record when using the CSV value. However, when I hardcode the string into the SOQL query, it works.
Object__c  obj = [Select Id, Name from Object__c where Name = 'Test Object'];
Please note that Object__c obj is a pre-existing object/record that exists prior to the execution of the Class so its existence is not dependent on any processes within the Class. Any assistance would be appreciated.
Best Answer chosen by Andrew Echevarria
Alexander TsitsuraAlexander Tsitsura
Maybe problem with field value, can you try trim this value?
 
field = field.trim();

I think that after parse csv this value contains spaces, if it not help try to use system debug for determine actual value
 
String field = csvRow[4]);  
System.debug('************* <' +field + '>' );
Object__c  obj = [Select Id, Name from Object__c where Name =: field];

Thanks,
Alex

All Answers

Alexander TsitsuraAlexander Tsitsura
Hi Andrew,

Error "caused by: System.QueryException: List has no rows for assignment to SObject". means that your query return nothing. You can query records to list and check list size.
Object__c[]  obj = [Select Id, Name from Object__c where Name ='Test Object'];
if (obj.size() > 0) {
  // records exists
} else {
  // no exists recotds
}

Thanks,
Alex
Andrew EchevarriaAndrew Echevarria
Yes, I understand the error, but I don't understand why it returns nothing if my code appears to be correct.
Alexander TsitsuraAlexander Tsitsura
Maybe problem with field value, can you try trim this value?
 
field = field.trim();

I think that after parse csv this value contains spaces, if it not help try to use system debug for determine actual value
 
String field = csvRow[4]);  
System.debug('************* <' +field + '>' );
Object__c  obj = [Select Id, Name from Object__c where Name =: field];

Thanks,
Alex
This was selected as the best answer
Andrew EchevarriaAndrew Echevarria
I can confirm that trimming the value worked! Thank you.
sheema R 6sheema R 6

due to extra spaces apex cannot read the values from CSV in a query. trimming the values will resolve the problem 

string.trim();