Skip to content

🔥 Join 600+ readers. Get our newsletter for code and tips.

How to Delete Query Activities in Bulk Using SSJS in Salesforce Marketing Cloud
314 views

How to Delete Query Activities in Bulk Using SSJS in Salesforce Marketing Cloud

View favourites

If you’ve worked in Salesforce Marketing Cloud Engagement long enough, you’ve probably accumulated hundreds, or even thousands, of Query Activities. Many were used once. Some were just for testing. And eventually, someone will say it: “We need to clean up unused query definitions.”

Cleaning them up manually in Automation Studio is painful. There’s no native bulk delete. Even in Contact Builder, where you can delete Data Extensions in batches of 200, it quickly becomes inefficient when you’re dealing with thousands of records.

You may have already guessed it this is the time where SSJS comes in to the rescue.

Retrieve query definitions using SSJS

Before we delete something we need to get list of query definitions we can play with and use it for our deletion process. This can’t be done any other way than with SSJS. Wasn’t this supposed to be a low/no-code platform? It feels like we end up writing more code than not. Anyway…

<script runat="server">
    Platform.Load("core", "1.1.1");
    var prox = new Script.Util.WSProxy();

    var cols = ["ObjectID", "Name", "CustomerKey"];
    var filter = {
            Property: "Name",
        SimpleOperator: "like",
        Value: "TEMP_%"
    };

    var moreData = true;
    var reqID = null;
    var results = [];

    while (moreData) {
        var response = prox.retrieve("QueryDefinition", cols, filter, null, reqID);

        if (response && response.Results) {
            results = results.concat(response.Results);
        }

        moreData = response.HasMoreRows;
        reqID = response.RequestID;
    }

    Write(Stringify(results));
</script>

This example fetches all Query Activities starting with TEMP_.

Remove query definitions using SSJS

Before you connect the two script make sure you query the correct data that will be moved for

<script runat="server">
    Platform.Load("Core", "1.1.1");
    var api = new Script.Util.WSProxy(),
        res, 
        batch = [],
        toRemove = 
        [""]
    try{
        
        for (var i = 0; i < toRemove.length; i++){
                Write("Removing " + toRemove[i] +  " ...... " );
                res = QueryDefinition.Init(toRemove[i].substring(0, 36)).Remove();
                Write(res);
                Write("<br>");
           
        }
    }catch(e){
        Write(Stringify(e.Description));
    }
</script>

Alternatively you can use (new Script.Util.WSProxy()).deleteItem("QueryDefinition",{ObjectID: "xxx-xxx-xxx-xxx"}) but it did not worked for me and have used the version above.

<script runat="server">
Platform.Load("core", "1.1.1");

var prox = new Script.Util.WSProxy();

// assume results[] already populated

for (var i = 0; i < results.length; i++) {

    var deletePayload = {
        ObjectID: results[i].ObjectID
    };

    var deleteResponse = prox.deleteItem("QueryDefinition", deletePayload);

    Write("Deleted: " + results[i].Name + "<br>");
}
</script>

You can build a full-fledged solution where you regularly store query definitions in a Data Extension and use it as your source of truth to decide which Query Activities should be removed.

Save query definitions into data extension

Create data extension with following fields

query_definition_info

Data extension to hold query definitions Fie…

🔒 Premium Subscriber Content

What you can learn with Premium

Unlock the full article to explore these topics in detail.

  • Save query definitions into data extension
    • query_definition_info
  • Save automation and automation activities
    • automations_list_information
    • automation_activities_list_information
    • Linking query definitions with automation

Already a Premium subscriber? Log in to continue reading, or register to create your account.

You must log in and have a Premium Subscriber account to read the full article.

When upgrading, please use the same email address as your WordPress account so we can correctly link your Premium membership.

Please allow us a little time to process and upgrade your account after the purchase. If you need faster access or encounter any issues, feel free to contact us at info@martechnotes.com or through any other available channel.

To join the Discord community, please also provide your Discord username after subscribing, or reach out to us directly for access.

You can subscribe even before creating a WordPress account — your subscription will be linked to the email address used during checkout.

Premium Subscriber

29,99 € / Year

  • Free e-book with all revisions - 101 Adobe Campaign Classic (SFMC 101 in progress)
  • All Premium Subscriber Benefits - Exclusive blog content, weekly insights, and Discord community access
  • Lock in Your Price for a Full Year - Avoid future price increases
  • Limited Seats at This Price - Lock in early before it goes up
  • Monthly 15-Minute Call - Discuss any topic directly

Oh hi there 👋
I have a SSJS skill for you.

Sign up now to get an SSJS skill that can be used with your AI companion

We don’t spam! Read our privacy policy for more info.

Share With Others

The author
Marcel Szimonisz Platinum

Marcel Szimonisz

Marketing Automation Consultant

I specialize in solving marketing technology challenges, automating processes, and turning ideas into practical solutions with Salesforce Marketing Cloud and Adobe Campaign. Through MarTechNotes, I share technical guides and insights that make complex topics easier to understand

Latest badges
Weekend Regular Weekend Regular Profile Complete Profile Complete Simple Start Simple Start 5 Day Streak 5 Day Streak First Comment First Comment

Your email address will not be published. Required fields are marked *

Get exclusive tips, scripts and news

Choose your topics

We don’t spam! Read our privacy policy for more info.

Similar posts

Add to this article

Share your experience

Your contribution

Article history

What changed