I have a method that should return an "Id" when it finds a record, but if it does not find a matching record then it can't return an Id. For example, I run a query on the Account object:

private static Id getID( String param ) {

 List<Account> accList = [SELECT Id FROM Account WHERE customField__c = : param ];
 if (accList.size() > 0 ) {
  return accList[0].Id;
 else {


My question is the code that calls the getId() method throws an error because when a record is not found I am not returning any Id back to the calling code, In a perfect world, I would have an Account record always that matched by criteria in the query, but this isn't the reality. How can I have the best of both worlds where when it does find a matching record it returns the Id, but when it doesn't I am not sure how to handle that.

  • 1
    Can you return a null in the else statement? And then just handle a null return value to mean that no matching account was found when calling the getId method?
    – Instread
    Aug 27, 2020 at 0:36
  • The return type of the method is "Id". Wouldn't that throw an error? Aug 27, 2020 at 0:37
  • No, it should allow a return of null. You just can't assign null to an Id variable
    – Instread
    Aug 27, 2020 at 0:38

1 Answer 1


Null is the value you're looking for. It means "no value". You can also optimize your code as follows:

private static Id getID( String param ) {
  for(Account record: [SELECT Id FROM Account WHERE customField__c = :param limit 1]) {
    return record.Id;
  return null;

This gets rid of the empty list check.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .