+ Start a Discussion
Flora LiuFlora Liu 

How to query multiple objects in one soql query

What I have:
An accountId: '001R0000005Xk58IAC'

What I want to get:
1. Events based on the accountId.
Query I have: 
SELECT id FROM Event where AccountId = '001R0000005Xk58IAC'

2. EmailMessage based on the accountId (it's called relatedToId in emailMessage object).
Query I have: 
SELECT id FROM EmailMessage where relatedToId = '001R0000005Xk58IAC'

My question is, how can I use ONE query to get both of them?
Are there something like:
SELECT (Event.id, EmailMessage.id) from (Event, EmailMessage) where event.accountId = '001R0000005Xk58IAC' AND emailmessage.id = '001R0000005Xk58IAC'

By the way, I just need to get the number of the returned results, which means I just need to know the event.count + emailMessage.count, but I want to get them in one query.

Hi Flora Liu,

Uisng this way we can not retrive multiple object using soql.

1. If you want to retrieve mutiple object using SOQL then you can use Parent/ Child Relation ship in SOQL . 
SOQL Query :
List<Account> listOFAccount = [SELECT Id, (SELECT Id FROM Contacts), (SELECT Id FROM Opportunities) FROM Account];
System.debug('Accout : '+listOFAccount[0].Contacts);

2. And aslo you can retrieve multiple object uisng SOSL . Please find below example :
SOSL Query :
FIND {Test} IN ALL FIELDS RETURNING Account(Name), Contact(FirstName,LastName,Department)

If it helpful for you . Please mark best answer. 

Mohammad Rafi.
David Roberts 4David Roberts 4
Retrieving the sub query lists...
List<Account> lstAccounts = [SELECT Id, Name, (SELECT Id, Name FROM Contacts), (SELECT Id, Name FROM Opportunities) FROM Account];
List<Contact> lstContacts;
List<Opportunity> lstOpps;
for (account aa : lstAccounts) {
    system.debug('------ ');
    system.debug('Account: '+aa.Name);
    lstContacts = aa.Contacts;
    for (contact cc : lstContacts) {
        system.debug('Contact: '+cc.Name);
    lstOpps = aa.Opportunities;
    for (Opportunity oo : lstOpps) {
        system.debug('Opportunity: '+oo.Name);