ShowAll Questionssorted byDate Posted
Marry Stein

# Best practise multiple queries Vs loop&if statments

Hey guys,
i want to create a matrix table. Because there is no standard function for this case i have to create value by myself. I wonder what is the best solution for this ?  Multiple queries like option 1 or one query like in option 2 ?

```// Option 1

public void getIntegers(){
List<AggregateResult> Monday = [SELECT Count(id)cnt  From task WHERE Weekday__c = 'Monday'];
mo = Integer.valueOf(Monday[0].get('cnt'));
List<AggregateResult> Tuesday = [SELECT Count(id)cnt  From task WHERE Weekday__c = 'Tuesday'];
tu = Integer.valueOf(Tuesday[0].get('cnt'));
List<AggregateResult> Wednesday = [SELECT Count(id)cnt  From task WHERE Weekday__c = 'Wednesday'];
we = Integer.valueOf(Wednesday[0].get('cnt'));
List<AggregateResult> Thursday = [SELECT Count(id)cnt  From task WHERE Weekday__c = 'Thursday'];
th = Integer.valueOf(Thursday[0].get('cnt'));
List<AggregateResult> Friday = [SELECT Count(id)cnt  From task WHERE Weekday__c = 'Friday'];
fr = Integer.valueOf(Friday[0].get('cnt'));
}

// Option 2

public void getCalls(){
List<Task> tskList = [SELECT Id, Weekday__c FROM Task ];
for(task t : tskList){
if(t.Weekday__c.equals('Monday')){
mond = mond +1;
} else if (t.Weekday__c.equals('Tuesday')){
tues = tues + 1;
} else if (t.Weekday__c.equals('Wednesday')){
wedn = wedn + 1;
} else if (t.Weekday__c.equals('Thursday')){
thur = thur + 1;
} else if (t.Weekday__c.equals('Friday')){
frid = frid + 1;
}
}
}```

Best Answer chosen by Marry Stein
Raj Vakati
I can suggest going with option 2  .. its not good to have too many SOQL in a single transaction

But instead of an if-else use switch statement

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_switch.htm

### All Answers

Raj Vakati
I can suggest going with option 2  .. its not good to have too many SOQL in a single transaction

But instead of an if-else use switch statement

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_switch.htm
This was selected as the best answer
Marry Stein
Thanks for your Answer Raj !