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
Tom FrayTom Fray 

Best Practice for getting 1 record in a SOQL query

Can anyone tell me the best way to use SOQl in a method to return 1 ID? The method should accept a string, and return the ID of a record with that string?
The method is called in a second method, when the ID is needed.
At some point, I would like the user to see a user friendly error if the SOQl query returned 0 or 2 or more results.
The user will be an admin running the code in execute anonymous at the moment, but i might move it to VF at some point.

Here is what i have so far,
Thanks
 
public string campaignName;
    public ID findCampaign(string campaignName){
    	list<Voucher_Marketing_Campaign__c> campaignIDs = [select id from Voucher_Marketing_Campaign__c where name = :campaignName];
    	if(campaignIDs.size() == 1){
    		return campaignIDs[0].id;
    	}
    	else{
    		return null;
    	}
    }
Part of the execute anonymous:
 
GiftCardMultiVoucherCreation g = new GiftCardMultiVoucherCreation();
    g.campaignName = 'App Promo July 2014';


 
Best Answer chosen by Tom Fray
bob_buzzardbob_buzzard
What you've done there is exactly right, I'd say. You've assigned the results to a list so that if the number of matches isn't exactly one that won't cause a problem. 

All Answers

bob_buzzardbob_buzzard
What you've done there is exactly right, I'd say. You've assigned the results to a list so that if the number of matches isn't exactly one that won't cause a problem. 
This was selected as the best answer
Tom FrayTom Fray
Hi Bob,

That's what I thought, but when I run the code, I get this error - System.QueryException: List has no rows for assignment to SObject

...whilst typing this reply, i've realised that the error is referring to another query in the same class. I am running it in a sandbox where a required account hadn't been set up.

The code I amended is working fine.

Thanks!