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
Chamil MadusankaChamil Madusanka 

Update query in SOQL

Hi,

I'm new to salesforce, APEX and SOQL. I want to know, how can we update some record using SOQL in APEX code?

Best Answer chosen by Admin (Salesforce Developers) 
bob_buzzardbob_buzzard

You can't update records using SOQL - it is a query only language.

 

You would update record using Data Manipulation Language (DML).  E.g. to query a record and then update it you could use the following snippet:

 

 

List<Contact> conts=[select id, Email, Description from Contact where email='keir.bowden@googlemail.com' limit 1];

if (!conts.isEmpty())
{
   Contact cont=conts[0];
   cont.Description='Updated description';
   update cont;
}

 

More information on DML is available in the Apex Developer's Guide at:

 

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_dml.htm?SearchType=Stem&Highlight=DML|dml

 

All Answers

bob_buzzardbob_buzzard

You can't update records using SOQL - it is a query only language.

 

You would update record using Data Manipulation Language (DML).  E.g. to query a record and then update it you could use the following snippet:

 

 

List<Contact> conts=[select id, Email, Description from Contact where email='keir.bowden@googlemail.com' limit 1];

if (!conts.isEmpty())
{
   Contact cont=conts[0];
   cont.Description='Updated description';
   update cont;
}

 

More information on DML is available in the Apex Developer's Guide at:

 

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_dml.htm?SearchType=Stem&Highlight=DML|dml

 

This was selected as the best answer
Chamil MadusankaChamil Madusanka
Hi Bob, It works. Thanks
xyxy

Thanx.... Even this query help me too

NaypersMclgxNaypersMclgx

Can anyone tell me what's wrong?, I get this when I do that...

 

System.LimitException: pato:DML currently not allowed
Class.pato.ListOpportunities.getMyObjectOpportunities: line 354, column 1

 

The line 354 is where I have "update opp"

 

 thank you.

 

Chamil MadusankaChamil Madusanka

You can't execute DML in the Constructor (or call a method that executes DML from a Constructor)

 

If this is the controller for a VF page, you can use the action parameter on the page to directly execute addcomment, and that is allowed I believe.