Search code examples
salesforcesoql

Query two custom objects joining on the Name field


I want to create a join on two custom objects joining on the Name field. Normally joins require a lookup or master-detail relationship between the two objects, but I just want to do a text match.

I think this is a Salesforce limitation but I couldn't find any docs on whether this was so. Can anyone confirm this?


Solution

  • Yes, you can make a join (with dot notation or as subquery) only if there's a relationship present. And relationships (lookup or master-detail) can be made only by Id. There are several "mutant fields" (like Task.WhoId) but generally speaking you can't write a JOIN in SOQL and certainly can't use a text column as a foreign key.

    http://www.salesforce.com/us/developer/docs/soql_sosl/Content/sforce_api_calls_soql_relationships.htm#relate_query_limits

    Relationship queries are not the same as SQL joins. You must have a relationship between objects to create a join in SOQL.

    There are some workarounds though. Why exactly do you need the join?

    Apex / SOQL - have a look at SOQL in apex - Getting unmatched results from two object types for example. Not the prettiest thing in the world but it works. If you want to try something really crazy - SOSL that would search your 2 objects at the same time?

    Reports - you should have no problem grouping by text field - that means a joined report might give you results you're after. Since Winter'13 joined reports allow charts and exporting, that was quite a limiting factor...

    Easy building of links between data - use external ids and upsert operation, especially if you plan to load data from outside SF easily. Check my answer for Can I insert deserialized JSON SObjects from another Salesforce org into my org?

    Uniqueness constraints - you can still mark fields as required & unique.

    Check against "dictionary" of allowed values - Validation rule with VLOOKUP might do what you're after.