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
Sonali Sharma 54Sonali Sharma 54 

Delete the Selected sObject or field from Org using apex

Need to delete custom lookup field from the Apex class
Karthik PadmakumarKarthik Padmakumar
By delete - do you mean delete from the object and then remove the references from Apex Classes? or are you trying to actually delete using Apex? (Metadata API)
Karthik PadmakumarKarthik Padmakumar
If it is the first (removing the references), you can extract all metadata after authenticating your org using VS Code or something and simply do a search in files to see the references. 
Sonali Sharma 54Sonali Sharma 54
@Karthik Padmakumar We are trying to delete the custom fields through the apex code.
Karthik PadmakumarKarthik Padmakumar
Hi Sonali, 

Upon some research, I am not really sure if that is possible (would be happy to learn if otherwise) - https://ideas.salesforce.com/s/idea/a0B8W00000Gdm2SUAR/ability-to-update-metadata-from-apex-apex-metadata-api

Side note - I'm not really sure on your use case but if you are trying to mass delete, you can always leverage any deployment tool or even VS Code.

Thanks,
Karthik
SwethaSwetha (Salesforce Developers) 
HI Sonali,
You should be able to delete custom fields via metadata API

From https://salesforce.stackexchange.com/questions/362784/delete-customfield-using-tooling-api, If you need to delete CustomField metadata through an API, then using deploy() through the Metadata API is likely the way to go. You will need to deploy destructive changes to the org. An example destructiveChanges.xml file:
 
<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
    <fullName>deletingfield</fullName>
    <types>
        <members>Account.Custom_Field__c</members>
        <name>CustomField</name>
    </types>
    <version>53.0</version>
</Package>

Related:
https://github.com/financialforcedev/apex-mdapi/issues/112

Creating custom field using Metadata API : https://developer.salesforce.com/forums/?id=9062I000000IXiyQAG

If this information helps, please mark the answer as best. Thank you
Sonali Sharma 54Sonali Sharma 54
Thank you Karthik and Swetha. Will check both methods and revert back if needed more help.