0

I've seen in a few places it seems likes people are directly mapping their query over to a custom apex object. E.g.

MyObject myObject = [SELECT fields FROM object WHERE cond];

Is this possible? If so, what does my class need to look like for everything to map correctly?

2

Yes, this is actually very common, but with SObjects instead of Apex classes.

I have a feeling that if you look harder at those examples, they'll all be SObjects like Account, Contact, SomeCustomObject__c, etc...

While the official documentation does say that a SOQL query will return a List<SObject>1, the result of a SOQL query can be automatically converted to a List of a more specific type.

For example, the following is very common (and perfectly valid)
List<Opportunity> myOpps = [SELECT Id FROM Opportunity LIMIT 10];

While not really advised2, you can extend this to assigning a single variable of your target SObject type (provided that your query returns exactly one record)

1: ...unless you throw in a GROUP BY clause and/or use some aggregate functions like SUM(), in which case the query will return a List<AggregateResult>
2: Assigning a query to a single variable instead of a collection will cause an exception if your query returns anything other than one row. 0 rows or 2+ rows = error. The safest way to go about this is to always assign the result of a query to a collection

| improve this answer | |

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.