You need to sign in to do that
Don't have an account?
Bahtiyar Ishkabulov
Filter SOQL query by multiple fields
Hi everyone,
How to filter a SOQL query by two or more fields (key fields)? For example let's say I have an object with three fields: Person (String), Year (String) and Income (Number). Person and Year are key fields. And there are four records in the object:
Person Year Income
'Jhon' '2016' 1000
'Jhon' '2017' 950
'Mike' '2016' 1100
'Mike' '2017' 900
Then I want to retrieve data about Jhon's income in 2016 and Mike's income in 2017
In some SQL implementations I can do it in such way:
How to filter a SOQL query by two or more fields (key fields)? For example let's say I have an object with three fields: Person (String), Year (String) and Income (Number). Person and Year are key fields. And there are four records in the object:
Person Year Income
'Jhon' '2016' 1000
'Jhon' '2017' 950
'Mike' '2016' 1100
'Mike' '2017' 900
Then I want to retrieve data about Jhon's income in 2016 and Mike's income in 2017
In some SQL implementations I can do it in such way:
Select Person, Year, Income From MyObject Where (Person, Year) In (('Jhon', '2016'), ('Mike', '2017'))What about SOQL? I was told that it won't accept such a query. Is there any means? Or I have to use "And" filter separately for every field and then use a loop?
All Answers
It won't work. Your query will return all four records, while I need only 2 of them (the first and the last).
Yes, I'm asking exactly how to put these conditional statements to lists (using "in" operator). Because it's just in my example there are only two filter pairs and it's not difficult to write them both directly in the query. But if there are 2000 filter pairs this method won't be possible at all.
I mean, if there were only one field, it would be as simple as: But I have two fields to match: Person and Year. So I need something like: And myList shoud contain other lists (massives) of two values: {{'Mike', '2017'}, {'Jhon', '2016'}...}
Yep, I did it just the same way now (but instead "|" used "_"). So this is the only possible way I guess?
P.S. Instead of formula field I made it just as a regular text field and fill it in with Field Update Workflow Action. This let me to make the field unique, so now I have a key of two fields.