I have a request I want to make very flexible because it will be used for a lightning custom component. The request should retrieve 1 id from 1 custom object tied to 1 standard object.

List<sObject> childRecord = 
[ SELECT id from RIB__c where RIB__c.Account__r.id =:parentId limit 1 ];

This request function for RIB and Account but I want to make it work for any combination of (custom/standard). I don't find the correct soql syntax and I don't know if it's even possible.

Edit: Yes after reading the doc you can't indeed put variables in the from clause. Does someone has found a workaroud?

Edit2: upvoted good answer. I just starting salesforce dev but it seems to be a good pratice to go this route, there are also some kind of "design patterns" for writting flexible requests (where you may or may not need clauses or clauses parts)

    public static String doGetChildId(String parentId, String parentType, String recordType){
        List<String> args = new List<String>();
        String query = 'select id from '+ args.get(0)+' where '+args.get(1)+'.id = '+ parentId+ ' limit 1';
        List<sObject> childRecord = Database.query(query);
        return (String)childRecord.get(0).get('id');            
  • 2
    What are you trying to achieve? Why do you need just one Id? If you are looking for the key prefix (first three characters) you can get it from the describe. – Adrian Larson Feb 8 '18 at 14:04
  • You still don't describe what you are trying to achieve or actually ask a question in this post. – Adrian Larson Feb 8 '18 at 14:48

You can use dynamic SOQL if you just want to get one arbitrary record Id:

public Id getArbitraryId(SObjectType sObjectType)
    String soql = 'SELECT Id FROM ' + sObjectType + ' LIMIT 1';
    SObject record = Database.query(soql);
    return record.Id;

If you just want the first three characters of Ids for that object, you can use the describe instead:

String keyPrefix = SObjectType.MyObject__c.getKeyPrefix();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.