I am trying to search account table by providing a search string. I am building a query based in different conditions and then adding the returned records in a list.The functionality is working correctly but I want to know how an below method be further optimized.    public PageReference search(){    clear();    runningUserId = Userinfo.getUserId();    String searchquery;    Boolean existUser = AccSearchAccess__c.getValues(runningUserId) !=null? true : false;    if(existUser){        searchquery='Select  Name,Id,AccessLevel__c FROM Account where Name like \'%'+accountName+'%\'';    }    else{        set<id> accountIds = new set<id>();        List<WMAccess__c> wmaLst = [Select id,Account__c from WMAccess__c where WM_User__c = : UserInfo.getUserId()];        for(WMAccess__c wm : wmaLst){            accountIds.add(wm.Account__c);        }        if(!accountIds.isEmpty()){            searchquery='Select  Name,Id,AccessLevel__c FROM Account where Name like \'%'+accountName+'%\' AND id IN:accountIds';        }    }    accList= Database.query(searchquery);    if(accList.size()>0)        for(Account acc : accList){            AccountWrapper aw = new AccountWrapper(acc, false);            aw.accountId = acc.id;             aw.accountName = acc.Name;            aw.accountAccess = acc.AccessLevel__c;            accountsList.add(aw);        }    return null;}
building a search functionality
java;performance;salesforce apex
You have exposed an injection vulnerability. 'WHERE Name like \'%'+accountName+'%\''Any time you merge user input into your query, you should call String.escapeSingleQuotes, or better yet, use a dynamic binding.// OKsearchQuery += 'WHERE Name LIKE \'%' + String.escapeSingleQuotes(accountName) + '%\'';// BETTERString fuzzySearchTerm = '%' + accountName + '%';searchQuery += 'WHERE Name LIKE :fuzzySearchTerm';