I have the ID of an object that could be either an account or a contact or a few other object types and want to query the name of the object regardless of the type and pass it to a string.

I am doing:
if(objectID.getSobjectType()==Contact.getSobjectType()){ name = [SELECT name FROM Contact WHERE id=:ObjectID].name; }else if(objectID.getSobjectType()==Account.getSobjectType()){ name = [SELECT name FROM Account WHERE id=:ObjectID].name; }...
Is there a better way to do this without using if that also works with querying custom fields?

  • are you bothered about Soql limits? Jun 17, 2015 at 14:04

2 Answers 2


Its hardly elegant, but you can use dynamic SOQL for this:

Id objectID = ...;
String name = (String) Database.query(
        'select Name from ' + objectID.getSobjectType() + ' where id = :objectID'

Also see the methods defined for SObject that allow you to write code that isn't tied to a specific type. The above uses get(String fieldName).

String[] startObj = new String[]{ objectID.getSobjectType() };
Schema.DescribeSObjectResult[] stObj = Schema.describeSobjects(startObj);
Schema.DescribeSObjectResult obj = stObj[0];

List<String> fields;

for (Schema.DescribeSObjectResult.feilds f : obj)

Schema.SObjectType objType = obj.getSObjectType();

String qry String.format(Select {0} from {1} Where Id =:{2}, new List<String>{fields, objType, objectId});


Something along those lines should work, i didn't test this so probably a-couple of compile errors but i'm sure you will be able to figure it out with google :)

  • If you know the fields you are after don't bother describing the object just put them in Jun 17, 2015 at 14:15

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .