0

I want to check if all the records have the same values for "Group__c" field and throw a message if the values are different.

Example data:

enter image description here

If all the records are of the same group(Group-A in this example), then no need to display an error. Since, the 3rd record belongs to Group-B - I want to display a message.

My SOQL query:

List <EmployeeContact__c> = 

[SELECT ID, Company__c, Contact__c, Country__c, Group__c 
FROM EmployeeContact__c
WHERE Parent__c = 'Parent-1' GROUP BY Group__c ] ; 

System.Debug('All employees for Parent-1 should be of same group');

How to query if there are any distinct values?

1 Answer 1

2

The query itself is only responsible for returning data. If you want to throw an error (or return a message), you'll have to inspect the results.

Given what you've told us, all you really need to do here is check to see how many rows your query returns.

I believe that using GROUP BY means that you'll always get a List<AggregateResult> returned (and that you need to add the other fields to the GROUP BY, use them in an Aggregate Function like COUNT(), or remove them).

List<AggregateResult> groupsList = [SELECT Group__c FROM EmployeeContact__c WHERE Parent__c = :myParent GROUP BY Group__c];

if(groupsList.size() > 1){
    // there is more than one group
    // prepare your error/message
}

You must log in to answer this question.

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