3 - DML

DML statements are

INSERT / UPDATE / DELETE / UNDELETE


TO DEBUG THE DML

Check the Filter in the Execution Logs 


INSERT

the Object Class is copied from API Name


// Inserting one single account

Account acc = new Account(Name='CLR Infotech', Phone='9988998899');

acc.Rating = 'Hot';

insert acc;

OR 

create a list and do

insert accounts

OR

// Alternate way to insert the accounts

Database.insert(accounts, false);  You can use allorNone or false


Database Methods vs. DML Statements in Salesforce:
FeatureDatabase MethodsDML Statements
Error HandlingSupports partial success with allOrNone=falseEntire transaction fails on any error
Return TypeReturns SaveResult/DeleteResult for each recordThrows DmlException on failure
Bulk ProcessingSuited for bulk processing with granular controlLimited control, less suitable for bulk
Usage in TriggersPreferred when selective transaction control neededCommon for simpler trigger scenarios
PerformanceSlightly slower due to added processingGenerally faster for straightforward cases
Use CaseComplex operations needing control and error detailSimple, non-bulk operations

DML

try {
    insert myRecords;
} catch (DmlException e) {
    // Handle exception if any record fails
}

Database Methods

Database.SaveResult[] results = Database.insert(myRecords, false);
for (Database.SaveResult result : results) {
    if (!result.isSuccess()) {
        // Handle individual record failure
    }
}

DELETE / UNDELETE

// get all accounts to delete
List<Account> accounts = [SELECT Id FROM Account WHERE Name LIKE 'Nidhi%'];
// delete using dml statement
delete accounts;
OR
// delete using database methods
//Database.delete(accounts);

// get deleted account records
List<Account> deletedAccounts = [SELECT Name, Phone FROM Account WHERE isDeleted=true ALL ROWS];
//undelete records
undelete deletedAccounts;





Comments

Popular posts from this blog

API Names in Salesforce

18 - LWC - BEST PRACTICES - For accessing HTML elements and their values in JavaScript

6 - Object Relationships (Lookup and Master-Detail and Junction Objects)