0

For example a have account sobject and want to use record to create another record with mainly that record data. So same name and another fields, but some fields with another data. Is it possible to do without specify all fields? Something like that, but without specify all fields? or at least not specify them in select?

Account account = [ Select id, name, some__c, some2__c  from Account Limit 1];
Account acc = new account( name = account.name, some__c = account.some__c, some2__c = 'some2__c'];
insert acc
3

Your data needs to come from somewhere. If you have the data "in memory" (that is, you already have an SObject instance with your data), then you don't need to query.

If you don't have (or can't construct data from) the data "in memory", then you will need to query for it. When you write a query, it's just a fact of life that you need to explicitly include every field you want to use later1.

The one thing that you can do to make your life easier is to use the clone() method that the SObject class provides (Account, Contact, MyCustomObject__c are all SObjects).

So something like

Account baseAccount = [SELECT Id, Name, Field1__c, Field2__c FROM Account LIMIT 1];
// first argument tells us to discard the Id from the record we're cloning
// second argument is deepclone (true) vs shallow clone (false, default) which, last
//   time I looked at it, doesn't behave as the documentation would suggest
// third and fourth arguments are to preserve read-only timestamps and autonumber
Account clonedAccount = baseAccount.clone(false, false, false, false);
insert clonedAccount;

1: There is the FIELDS() function that was somewhat recently introduced, but you can only use FIELDS(STANDARD) in Apex, so any custom fields still need to be explicitly queried. Retreiving fields you don't need will also take up additional heap space. That doesn't sound like a concern here, but it is something to keep in mind.

2
  • Wish I could give an additional +1 for the awesome use of superscript.
    – Moonpie
    Sep 28 at 14:56
  • Thanks, awesome.
    – meximah
    Sep 28 at 15:03

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.