How to select Unique values in SOQL

You don't have the distinct keyword in SOQL I'm afraid - you'll need a coded workaround.

Wes Nolte wrote a blog post explaining how to do this a few years ago:

http://th3silverlining.com/2009/06/28/soql-distinct-keyword/

Backup in case blog goes down:

Apex trick that can be employed as a work-around

public static List<String> getDistinctLastnames(List<String> duplicates){
    List<String> distinctLastnames = new List<String>();
    for(String lastname: duplicates){
        Boolean found = false;
        for(Integer i=0; i< distinctLastnames.size(); i++){
        //Check if current lastname has been added yet
        if(lastname.equalsIgnoreCase(distinctLastnames[i])){ 

            found=true;
            break;
        }
    }
    if(!found)
        distinctLastnames.add(lastname);
    }
    return distinctLastnames;
}

A SOQL alternative to selecting distinct rows:

SELECT name, COUNT(Id)
FROM Lead
GROUP BY name

Shows you all of the distinct names, with how many of them there are.

One drawback is if there are too many rows in the table, it will just fail, just like sales force is in an existential way.


 List<zip__c> lstzips= [select id,name,ANNUAL_CALLS__c,city__c,state__c,No_Of_Targets__c,Territory_ID__c,Territory__r.name,Territory__r.ANNUAL_CALLS__c from zip__c where name in :sArr ];

 Map<String,zip__c> mapStrByzip=new Map<String,zip__c>();

for(zip__c zipone:lstzips){
    mapStrByLstzips.put(zipone.Territory_ID__c,zipone);//This is map and hence it will always have unique values 
}

system.debug('List return'+mapStrByLstzips.values());

Use Maps for this and make Territory_ID__c as key for the Map and that should give you unique values