Is it possible to delete an SObject by knowing only Id?

Here is what I found:

Id del = '003S00000099999'; // whatever ID you are deleting 
Contact ct = new Contact(Id = del); 
delete ct;

So, is it safe to always use a standard object like the Contact or maybe Account to delete records by knowing only Id? Or are there better ways of accomplishing this?

Just checked. The approach of using Contact does not work.

  • What do you mean by "[it] does not work"? That approach works fine provided you have the right kind of sObject for that Id. – David Reed Aug 20 at 13:21
  • You can delete record this way. Any delete triggers are being run as well in this case, and any lookups that restrict deletion are also taken into account. – rael_kid Aug 20 at 13:21
  • @DavidReed, I have only Id and I do not guarantee the type of object. – iloveseven Aug 20 at 13:22
up vote 9 down vote accepted

Yes, you can delete an object knowing only its Id.

If you know the object's type at development time, you can initialize an sObject instance with the Id and supply it to the delete DML operator, as you show:

Contact ct = new Contact(Id = del); 
delete ct;

If you don't know the object's type, you can pass the Id directly to Database.delete(), which as you noted has an overloaded variant that takes a record Id directly. You can also, if you do not know the Id's type at compile time, construct an sObject instance dynamically at runtime, which you can then pass to any and all Database methods and DML operations:

Account a = new Account(Name = 'Account');
insert a;

Id i = a.Id;
sObject q = i.getSobjectType().newSobject(i);
delete q;
  • 1
    The last option is exactly what I was looking for. – iloveseven Aug 20 at 13:37

Yes. You can delete the record by using only Id. Ideally it is not a good way to delete for major records. But you can restrict the deletion at profile level in object permissions. Instead of deleting records directly you can use multiple criteria and delete record.

  • It seems that Database.delete(myRecordId); is the best way to go here. – iloveseven Aug 20 at 13:25
  • 2
    Could you expand on your answer to explain what you mean by "it is not a good way to delete" and "use multiple criteria and delete record"? – David Reed Aug 20 at 13:29

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.