So we all know it is possible to directly select into a Map, like this:

Map<Id, Account> accounts = new Map<Id, Account>([SELECT Id, Name FROM Account]);

Is it possible to do the same thing, using Database.query()?

Map<Id, Account> accounts = new Map<Id, Account>(Database.query('SELECT Id, Name FROM Account'));

Sadly the latter doesn't seem to work.

up vote 7 down vote accepted

It could be that this is one scenario where the "magic casting" of Database.query doesn't work quite right.

How about:

Map<Id, Account> accounts = new Map<Id, Account>((List<Account>)Database.query('SELECT Id, Name FROM Account'));

Any luck?

  • Since you were first by 6 seconds - I'll accept yours. :) – Semmel Nov 20 at 10:23

Adding a bit of info here on top of other answers.

This works:

Map<Id, Account> accounts = new Map<Id, Account>([SELECT Id, Name FROM Account]);

Because the return type from the SOQL is that of Account.

This does not work:

Map<Id, Account> accounts = new Map<Id, Account>(Database.query('SELECT Id, Name FROM Account'));

Because the return type of Database.query is always SObject[]. So unless you cast the return type to the exact object type, it won't work.


Working versions.

Use SObject in your declaration

Map<Id, SObject> accounts = new Map<Id, SObject>(Database.query('SELECT Id, Name FROM Account'));

OR

As in other answers, cast it to list/array of account:

Map<Id, Account> accounts = new Map<Id, Account>((Account[])Database.query('SELECT Id, Name FROM Account'));

If you cast it to a List of the expected sObject type first it will work.

E.g.

Map<Id, Account> accounts = 
    new Map<Id, Account>((List<Account>)Database.query('SELECT Id, Name FROM Account'));
  • 5
    Ha! Beat you by 6 seconds. Just long enough to crack open a beer with my lovely deployment fish bottle opener :) – Charles T Nov 15 at 17:47
  • 🤨 I saw that quick edit in the 5 minute window. :) – Daniel Ballinger Nov 15 at 17:48
  • 2
    Hah yes, just a formatting gaffe. – Charles T Nov 15 at 17:51
  • I could swear that I tried casting it but - but obviously I didn't. It's working now. – Semmel Nov 20 at 10:22

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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