I have been looking for a SOQL distinct solution and how you can get only unique values from a SOQL expression. So I went about writing a method to return distinct values from a SObject. Call the distinct method as follows: SOQLUtils.distinct(‘StageName’, ‘Opportunity’) and it will return all the distinct StageNames for all your Opportunities.
I have added the test class which has 100% code coverage.
public with sharing class SOQLUtils { public static Set<String> getDistinct(String Field, String Table) { Set distinctSet = new Set(); List createAggregateListOfDistinctValues = Database.query('Select ' + Field + ' From ' + Table + ' where ' + Field + ' !=null Group By ' + Field); for (AggregateResult aggregateResult : createAggregateListOfDistinctValues) distinctSet.add((String)aggregateResult.get(Field)); return distinctSet; } public static boolean isDistinct(String Field, String Table) { return getDistinct(Field, Table).size() > 1 ? true : false; } @isTest static void getDistinctTest() { List testAccountList = new List(); for (Integer k=0; k < 200; k++) testAccountList.adD(new Account(Name='[Test]' + k)); insert testAccountList; System.assert(getDistinct('Name', 'Account').size() == 200); } @isTest static void getNotDistinctTest() { List testAccountList = new List(); for (Integer k=0; k < 200; k++) testAccountList.adD(new Account(Name='[Test]')); insert testAccountList; System.assert(getDistinct('Name', 'Account').size() == 1); } @isTest static void isDistinctTest() { List testAccountList = new List(); for (Integer k=0; k < 200; k++) testAccountList.adD(new Account(Name='[Test]' + k)); insert testAccountList; System.assert(isDistinct('Name', 'Account') == true); } @isTest static void isNotDistinctTest() { List testAccountList = new List(); for (Integer k=0; k < 200; k++) testAccountList.adD(new Account(Name='[Test]')); insert testAccountList; System.assert(isDistinct('Name', 'Account') == false); } }