You need to sign in to do that
Don't have an account?
Fatfox 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!
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!
You need to do it like this
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
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
You need to do it like this
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.
<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>