function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Fatfox FFatfox F 

Apex Beginner Doubt!

Hi all,

I'm a newbie in Apex and I have a doubt which is bugging me.
 
While acquiring Id of a particular record of an object, why do I have to create sObject (if I'm not wrong) and not create a variable of type ID?
 
Further details:

The following works correctly and gives me the Account Id.
Account acct = [Select Id from Account where Name='Test'];
System.debug('ID: '+acct.Id);
 
But the following throws an error.
ID id = [Select Id from Account where Name='Test'];
System.debug('ID: '+id);

Why so??

Please help and any additional information will be greatly appreciated.

Thanks guys!
Best Answer chosen by Fatfox F
Tushar Tyagi 4Tushar Tyagi 4
hey Fatfox F,
You need to do it like this
ID id = [Select Id from Account where Name='Test' limit 1].id;
System.debug('ID: '+id);

You need to mention Id there so that Salesforce will recognize that you want ID from account 



Mark as best answer if you get it.

All Answers

Amit Singh 1Amit Singh 1
Further details:

The following works correctly and gives me the Account Id.
Account acct = [Select Id from Account where Name='Test'];
System.debug('ID: '+acct.Id);
-- Here you are Querying the Whole Object which can store all the fields into this (acct ) variable. You can query many fields like 10,20,25 fields and can access like acc.Id, acc.Name.
In short in stores the whole object record

 
But the following throws an error.
ID id = [Select Id from Account where Name='Test'];
// Here if you want to fetch Record Id only then use below SOQL
ID id = [Select Id from Account where Name='Test'].Id; / this will return Id of the Account NAme Test

System.debug('ID: '+id);

Hope u got ur answer
Tushar Tyagi 4Tushar Tyagi 4
hey Fatfox F,
You need to do it like this
ID id = [Select Id from Account where Name='Test' limit 1].id;
System.debug('ID: '+id);

You need to mention Id there so that Salesforce will recognize that you want ID from account 



Mark as best answer if you get it.
This was selected as the best answer
Glyn Anderson 3Glyn Anderson 3
SOQL query results can be assigned to one of three data types: List<sObject>, sObject, Integer.

<pre>
List<Account> accounts = [SELECT Id FROM Account];    // returns a list of all Account records
Account account = [SELECT Id FROM Account LIMIT 1];    // returns a single Account record - throws an error if there are no Accounts
Integer numAccounts = [SELECT COUNT(Id) FROM Account];    // returns the number of Account records
</pre>