SOQL Queries - El Toro - Find articles about Visualforce, Apex, Force.com and Salesforce in general

Print Preview

SOQL Queries

This sample shows some common SOQLs and how to process them in Apex

Parent-to-child

String queryString = 'select id, parentField1, parentField2, (select Child_FieldName1, Child_FieldName2 from ChildObjectName limit 1) from ParentObject';
SObject[] queryParentObject = Database.query(queryString);
for(SObject parentRecord : queryParentObject){
    Object ParentFieldValue1 = parentRecord.get('parentField1');
    for(SObject childRecord : parentRecord.getSObjects('ChildObjectName')){
        Object ChildFieldValue1 = childRecord.get('Child_FieldName1');
        Object ChildFieldValue2 = childRecord.get('Child_FieldName2');
    }
    system.debug('Result: Parent value: '+ParentFieldValue1+'. First child field value: '+ChildFieldValue1);
}

Few objects (Inner query)

Set<ID> ids = new Set<ID>();
for (Case c : [Select Contact.AccountId From Case c]) {
    ids.add(c.Contact.AccountId);
}
for (Account acc : [SELECT (SELECT Name From Assets) From Account WHERE Id IN :ids]) {
    for (Asset ass : acc.Assets) {
        System.debug(ass.Name);   
    }
}

Three Objects

Select id, name, (select id, firstname, lastname from contacts) from account where id in (select accountid from opportunity where id = '0063000000NHnfIAAT')

comments powered by Disqus

© El Toro . IT @ 2013
Andrés Pérez