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