Write a GAQL High CPA Alert Script for Search Terms

Learn how to build a custom GAQL Google Ads script to detect runaway exact match queries exceeding 2.5x Target CPA and send instant Slack and email alerts.

By AdTurbo Team · 2026-11-28

Even tightly managed Google Ads accounts suffer from silent budget drains. You carefully structure an exact match ad group, set a sensible Target Cost Per Acquisition (tCPA), and assume Smart Bidding will safeguard your profit margins. Yet, due to auction spikes, intent shifts, or loose semantic matching, specific search terms quietly accumulate ad spend while driving zero or shockingly expensive conversions.

When a single search query costs 2.5 times your target CPA without driving acceptable return, every additional impression wastes your budget. While standard automated rules offer basic triggers, they lack granular control over search term metrics, custom mathematical thresholds, and modern multi-channel alerting.

By leveraging the Google Ads Query Language (GAQL) inside the modernized Google Ads Scripts engine, you can isolate exact match queries exceeding 2.5x your target CPA and push real-time notifications straight to Slack or your email inbox. Here is the complete technical walkthrough to build, deploy, and customize a high-precision GAQL alerting script.

---

Why Exact Match Queries Siphon Budget Above Target CPA

Many advertisers assume exact match still means exact literal match. Under Google’s close variant architecture, exact match keywords routinely match to synonyms, paraphrases, and intent variations that don't always convert at identical rates.

Even when a search term matches your keyword character for character, Smart Bidding algorithms evaluate context at auction time—user location, device, time of day, and past browsing behavior. Occasionally, the bidding engine tests aggressive bids on historical converters during high-competition windows, driving costs skyward before realizing the conversion rate has cratered.

The Failure Mode of Standard Automated Rules

Google Ads provides built-in automated rules, but they fall short for sophisticated query-level governance:

1. Keyword vs. Search Term Separation: Automated rules evaluate the keyword entity natively, not the underlying search term. If a broad or phrase keyword triggered three queries—two profitable and one burning $400 at a 4x target CPA—the blended keyword metrics obscure the problem.

2. Fixed Dollar Ceilings Only: Native rules struggle to calculate dynamic thresholds per campaign. If Campaign A has a $30 tCPA and Campaign B has a $120 tCPA, a static "Cost $100 and Conversions = 0" rule creates false positives on Campaign B while missing runaway waste on Campaign A.

3. Clunky Notification Options: Standard rules email generic tabular summaries that get lost in inbox clutter rather than dispatching actionable Slack pings with direct links to the offending entity.

Reviewing your search terms report manually every morning is one option, but automated detection eliminates human delay and catches runaway spend before weekend budgets vanish.

---

Understanding the Modern Google Ads Scripts Engine and GAQL

Google completely migrated the Google Ads Scripts platform to run on the Google Ads API architecture. The legacy AWQL (AdWords Query Language) syntax is obsolete, replaced by GAQL (Google Ads Query Language).

Core Differences Between AWQL and Modern GAQL

| Feature | Legacy AWQL (Deprecated) | Modern GAQL (Current) | Benefit for Advertisers |

| :--- | :--- | :--- | :--- |

| Syntax Style | SQL-like, flat column names | Object-oriented dot notation | Access to deeply nested entity data |

| Query Resource | KEYWORDSPERFORMANCEREPORT | searchtermview | True search query insights separated from keywords |

| Cost Precision | Formatted floating currency | metrics.costmicros (Integer) | Eliminates rounding errors in calculations |

| API Engine | Legacy AdWords API | Modern REST/gRPC Google Ads API | Faster execution and unified field schemas |

| Execution Speed | Slower iteration over iterators | Batch streaming via AdsApp.search() | Queries thousands of terms in seconds |

In modern GAQL, spend is stored in micros. One dollar equals 1,000,000 micros. If your target CPA is $50, the micro calculation is 50 1000000 = 50,000,000. Writing mathematical comparisons requires handling micros correctly before converting them back to readable dollar amounts in your alerts.

---

The Architecture of a GAQL High CPA Alert Script

To detect high CPA search queries with a Google Ads script, our script must execute five distinct steps:

1. Fetch Dynamic Campaign Targets: Query campaigns to establish their individual Target CPA. If a campaign lacks an explicit tCPA setting, the script applies an account-level fallback threshold.

2. Query the searchtermview via GAQL: Filter for search terms that served under exact match targeting within a specific lookback window (e.g., past 14 or 30 days).

3. Compute Actual CPA and Threshold Multipliers: Evaluate whether the search term has generated conversions. If it converted, calculate metrics.costmicros / metrics.conversions. If it generated zero conversions, compare metrics.costmicros directly against the CPA ceiling (2.5x target CPA).

4. Format Diagnostic Output: Structure data including campaign name, ad group name, query string, total spend, conversions, and actual CPA.

5. Dispatch Alerts: Push immediate payload notifications to a Slack webhook and dispatch a clean HTML email alert to the PPC management team.

For teams managing accounts with significant scale, pairing programmatic scripts with automated audit tools like the AdTurbo free audit helps identify historical spend bleeding before writing production code.

---

Writing the Complete GAQL High CPA Detection Script

Below is the complete, production-ready script. It evaluates both converting queries whose CPA exceeds 2.5x your campaign target, and zero-conversion queries whose raw spend has exceeded 2.5x target CPA.

javascript

/

• GAQL High CPA Search Term Alert Script

• Identifies exact match search terms exceeding 2.5x Target CPA

• and pushes alerts via Email and Slack Webhook.

/

const CONFIG = {

// Lookback window: LAST7DAYS, LAST14DAYS, LAST30DAYS

DATERANGE: 'LAST14DAYS',

// Threshold multiplier

CPAMULTIPLIER: 2.5,

// Fallback Target CPA in account currency if campaign has no explicit tCPA

FALLBACKTARGETCPA: 45.00,

// Minimum spend threshold in account currency to avoid flagging low-volume noise

MINSPENDTHRESHOLD: 20.00,

// Notifications

EMAILRECIPIENTS: ['[email protected]'],

SENDEMAIL: true,

// Slack Webhook Configuration (Leave empty string if not using Slack)

SLACKWEBHOOKURL: 'https://hooks.slack.com/services/YOUR/WEBHOOK/URL',

SENDSLACK: true

};

function main() {

Logger.log('Starting GAQL High CPA Search Term Analysis...');

const campaignCpaMap = getCampaignTargetCpas();

const offendingQueries = getRunawayExactQueries(campaignCpaMap);

if (offendingQueries.length === 0) {

Logger.log('No exact match queries exceeded the 2.5x Target CPA ceiling.');

return;

}

Logger.log(Found ${offendingQueries.length} search queries exceeding threshold.);

if (CONFIG.SENDEMAIL && CONFIG.EMAILRECIPIENTS.length 0) {

sendEmailNotification(offendingQueries);

}

if (CONFIG.SENDSLACK && CONFIG.SLACKWEBHOOKURL !== '') {

sendSlackNotification(offendingQueries);

}

}

/

• Queries campaigns to map their respective Target CPA settings.

/

function getCampaignTargetCpas() {

const campaignMap = {};

const query =

SELECT

campaign.id,

campaign.name,

campaign.targetcpa.targetcpamicros,

campaign.biddingstrategytype

FROM campaign

WHERE campaign.status = 'ENABLED'

;

const searchResults = AdsApp.search(query);

while (searchResults.hasNext()) {

const row = searchResults.next();

const campaignId = row.campaign.id;

let targetCpa = CONFIG.FALLBACKTARGETCPA;

if (row.campaign.targetCpa && row.campaign.targetCpa.targetCpaMicros) {

targetCpa = row.campaign.targetCpa.targetCpaMicros / 1000000;

}

campaignMap[campaignId] = {

name: row.campaign.name,

targetCpa: targetCpa

};

}

return campaignMap;

}

/

• Executes GAQL query against searchtermview to isolate runaway queries.

/

function getRunawayExactQueries(campaignMap) {

const results = [];

// Query search terms filtered by EXACT match type

const query =

SELECT

campaign.id,

campaign.name,

adgroup.name,

searchtermview.searchterm,

segments.searchtermmatchtype,

metrics.costmicros,

metrics.conversions,

metrics.clicks

FROM searchtermview

WHERE

segments.searchtermmatchtype = 'EXACT'

AND metrics.costmicros ${CONFIG.MINSPENDTHRESHOLD 1000000}

AND segments.date DURING ${CONFIG.DATERANGE}

;

const searchResults = AdsApp.search(query);

while (searchResults.hasNext()) {

const row = searchResults.next();

const campaignId = row.campaign.id;

const cost = row.metrics.costMicros / 1000000;

const conversions = parseFloat(row.metrics.conversions) || 0;

const clicks = parseInt(row.metrics.clicks, 10);

const searchTerm = row.searchTermView.searchTerm;

const targetCpa = campaignMap[campaignId]

? campaignMap[campaignId].targetCpa

: CONFIG.FALLBACKTARGETCPA;

const thresholdCpa = targetCpa CONFIG.CPAMULTIPLIER;

let isViolation = false;

let calculatedCpa = 0;

if (conversions 0) {

calculatedCpa = cost / conversions;

if (calculatedCpa = thresholdCpa) {

isViolation = true;

}

} else {

// Zero conversion spend exceeding 2.5x Target CPA

calculatedCpa = cost;

if (cost = thresholdCpa) {

isViolation = true;

}

}

if (isViolation) {

results.push({

campaignName: row.campaign.name,

adGroupName: row.adGroup.name,

searchTerm: searchTerm,

clicks: clicks,

cost: cost.toFixed(2),

conversions: conversions.toFixed(1),

effectiveCpa: calculatedCpa.toFixed(2),

targetCpa: targetCpa.toFixed(2),

thresholdCpa: thresholdCpa.toFixed(2),

type: conversions === 0 ? 'Zero Conversions' : 'High Actual CPA'

});

}

}

return results;

}

/

• Dispatches an HTML table email to configured recipients.

/

function sendEmailNotification(violations) {

const accountName = AdsApp.currentAccount().getName();

const subject = [High CPA Alert] ${violations.length} Exact Match Queries Breached Ceiling in ${accountName};

let htmlBody = Google Ads Runaway CPA Alert: ${accountName};

htmlBody += The following exact match queries exceeded ${CONFIG.CPAMULTIPLIER}x Target CPA over the ${CONFIG.DATERANGE} window:;

htmlBody += ;

htmlBody += CampaignAd GroupSearch TermClicksCostConvActual CPATarget CPAThresholdIssue;

violations.forEach(v = {

htmlBody +=

${v.campaignName}

${v.adGroupName}

${v.searchTerm}

${v.clicks}

${v.cost}

${v.conversions}

${v.effectiveCpa}

${v.targetCpa}

${v.thresholdCpa}

${v.type}

;

});

htmlBody += Recommended Action: Review these terms immediately and evaluate them for negative keyword exclusions or bid adjustments.;

MailApp.sendEmail({

to: CONFIG.EMAILRECIPIENTS.join(','),

subject: subject,

htmlBody: htmlBody

});

Logger.log('Email alert successfully dispatched.');

}

/

• Dispatches a structured alert payload to a Slack Webhook.

/

function sendSlackNotification(violations) {

const accountName = AdsApp.currentAccount().getName();

const textHeader = 🚨 Google Ads High CPA Alert: ${accountName}\nFound ${violations.length} exact match search terms exceeding ${CONFIG.CPAMULTIPLIER}x target CPA.;

const blocks = [

{

type: "section",

text: { type: "mrkdwn", text: textHeader }

}

];

// Show top 5 worst offenders directly in Slack to keep payload compact

const topOffenders = violations.slice(0, 5);

let detailText = "";

topOffenders.forEach(v = {

detailText += • "${v.searchTerm}" in ${v.campaignName}\n Spend: ${v.cost} | Conv: ${v.conversions} | CPA: ${v.effectiveCpa} (Target: ${v.targetCpa})\n;

});

if (violations.length 5) {

detailText += ...and ${violations.length - 5} more queries sent via email.;

}

blocks.push({

type: "section",

text: { type: "mrkdwn", text: detailText }

});

const payload = JSON.stringify({ blocks: blocks });

const options = {

method: 'post',

contentType: 'application/json',

payload: payload,

muteHttpExceptions: true

};

UrlFetchApp.fetch(CONFIG.SLACKWEBHOOKURL, options);

Logger.log('Slack alert successfully dispatched.');

}

---

Setting Up the Script in Google Ads Step by Step

Implementing scripts takes less than ten minutes. Follow these exact steps inside your account:

1. Access the Script Editor

1. Sign in to your Google Ads account.

2. In the top navigation or left sidebar, navigate to Tools Bulk Actions Scripts.

3. Click the blue + button to create a new script.

2. Paste and Configure Parameters

1. Replace any placeholder boilerplate text in the editor with the script code provided above.

2. Update CONFIG.EMAILRECIPIENTS with your team's email addresses.

3. If you want Slack notifications, create an Incoming Webhook in your Slack workspace and paste the URL into CONFIG.SLACKWEBHOOKURL.

4. Tune CONFIG.CPAMULTIPLIER (default is 2.5) and CONFIG.MINSPENDTHRESHOLD ($20 prevents low-impression queries from triggering false alarms).

3. Authorize the Script

Click Authorize at the bottom right. A Google OAuth modal will appear asking for permissions to manage Google Ads campaigns and access external services (UrlFetchApp for Slack and MailApp for Email). Grant permissions under your authorized Google account.

4. Run a Preview Test

Never schedule a script without running a dry run. Click Preview. Inspect the Logs tab at the bottom. The script will output its progress line by line:

text

Starting GAQL High CPA Search Term Analysis...

Found 3 search queries exceeding threshold.

Email alert successfully dispatched.

Slack alert successfully dispatched.

Check your email and Slack channel to confirm formatting and accuracy.

5. Schedule Execution

Once the preview runs cleanly, click Save. On the main Scripts dashboard, find your new script and set the Frequency column to run Daily (typically between 5:00 AM and 7:00 AM in your account’s local timezone).

---

Deep Dive: Critical GAQL Fields and Edge Cases

Understanding the mechanics of GAQL helps you customize this script without breaking your reporting logic.

Why segments.searchtermmatchtype Matters

In the searchtermview resource, Google Ads distinguishes between the keyword match type and the search term match type:

• adgroupcriterion.keyword.matchtype: The match type assigned to your keyword in the ad group.

• segments.searchtermmatchtype: How the user's actual query matched to your keyword (EXACT, PHRASE, or BROAD).

Our script filters on segments.searchtermmatchtype = 'EXACT'. This includes close variants that Google forced into the exact matching bracket. This is where most PPC managers discover search terms that strayed far from historical relevance.

Handling Conversion Latency

Conversion delay is a real challenge for automated alerting. If your business has a 7-day average sales cycle from first click to completed purchase, looking at queries from the LAST7DAYS will inflate CPA artificially because the ad spend has registered but the conversion has not.

To manage conversion latency:

• For transactional e-commerce with immediate checkout: Set DATERANGE to LAST7DAYS or LAST14DAYS.

• For B2B lead gen with longer pipelines: Set DATERANGE to LAST30DAYS and elevate the MINSPENDTHRESHOLD.

• Use our comprehensive PPC audit checklist to evaluate your account's baseline conversion lag before choosing an alert window.

Dealing with Portfolio Bid Strategies

If your campaigns rely on Portfolio Bidding Strategies rather than individual campaign-level Target CPA settings, campaign.targetcpa.targetcpamicros may return null in standard queries. In the provided script, our fallback mechanism catches this scenario:

javascript

if (row.campaign.targetCpa && row.campaign.targetCpa.targetCpaMicros) {

targetCpa = row.campaign.targetCpa.targetCpaMicros / 1000000;

} else {

targetCpa = CONFIG.FALLBACKTARGETCPA;

}

This ensures that even complex portfolio setups receive baseline protection without script crashes.

---

Action Matrix: What to Do When a Query Triggers an Alert

Receiving an alert is only half the battle. When an exact match search query crosses the 2.5x threshold, follow this triage workflow:

[Alert Received: Term 2.5x tCPA]

│

Is the term high buying intent?

/ \

YES NO

/ \

Check Landing Page Add as Negative Keyword

& Technical Conversion (Ad Group or Shared List)

Tracking Integrity

│

Are tracking & page sound?

/ \

YES NO

/ \

Isolate to Single Fix Conversion Friction /

Keyword Ad Group Page Load Errors

& Lower Max CPC

1. Query Relevance Check

Is the term genuinely relevant to your service offering? If it is a loose variant that slipped through Google's semantic net (e.g., matching "industrial plumbing contractor" to "residential plumbing license course"), add it immediately as an exact negative keyword. You can pull additional variations using our guide on how to find negative keywords.

2. Conversion Tracking Audit

If a historically dependable exact match term suddenly posts 40 clicks and 0 conversions, do not immediately assume demand vanished. Check if tracking tags dropped off the destination URL, or if a form submission error is breaking your conversion funnel.

3. Isolation into Single Keyword Ad Groups (SKAGs) or Custom Bidding

If the query represents high buying intent that you must win, do not let an automated campaign bid blindly on it. Isolate the term into its own ad group or campaign with manual CPC or target impression share bidding, allowing you to set a rigid bid ceiling.

---

Manual Scripts vs. Autonomous Optimization Platforms

While custom GAQL scripts give developers absolute transparency, maintaining custom code across dozens of accounts requires ongoing developer overhead.

| Capability | Custom GAQL Scripts | Dedicated Google Ads Automation (e.g., AdTurbo) |

| :--- | :--- | :--- |

| Cost | Free (Internal time investment) | $149/mo (Flat, 7-day trial with card) |

| Setup Difficulty | Intermediate (Requires JS/GAQL) | Zero-code (Click-to-connect API) |

| Alert Flexibility | Fully customizable via Webhooks | Native multi-channel alerts & dashboards |

| Action Automation | Must write manual mutation logic | Autonomous bid adjustments & negative insertion |

| Maintenance | Manual updates when API versions change | Continuous background updates & machine learning |

| Cross-Account Scale | Requires MCC Script scaffolding | Native multi-account portfolio management |

Writing custom scripts is ideal for solo engineers and technically sophisticated PPC teams who require exact rule configurations. For agencies managing substantial client portfolios without dedicated in-house developers, purpose-built PPC management software like AdTurbo automates high CPA pruning, negative keyword harvesting, and bidding anomalies continuously behind the scenes.

---

Related Guides

• How to Use the Google Ads Search Terms Report to Cut Wasted Spend

• How to Find Negative Keywords in Google Ads (Step by Step)

• PPC Audit Checklist: 12 Steps to Fix a Leaking Google Ads Account

---

Frequently Asked Questions

Can this GAQL script automatically add negative keywords instead of just alerting?

Yes, you can extend the script using the AdsApp.createNegativeKeyword method to exclude terms automatically. However, automatically adding negatives to exact match queries carries high risk, as conversion delays or temporary server outages could cause you to unintentionally block core business revenue drivers. We recommend using alerts for review first.

Why does the script use searchtermview instead of the keyword report?

The keyword report evaluates the keyword entity you deliberately added to your ad group, whereas searchtermview reflects the literal search strings users entered before clicking your ads. Because Google's exact match keywords match to close semantic variants, tracking performance at the searchtermview level is essential to identify actual cost anomalies.

Will this script work in a Google Ads MCC (Manager) account?

To run this across multiple accounts from an MCC, you must wrap the core logic inside the AdsManagerApp.accounts().select() iterator. The script shown here is designed for single-account execution, but the underlying GAQL queries and data structures remain identical when migrating to MCC script containers.

How does the script calculate spend for queries with zero conversions?

When a search query accumulates spend without generating any conversions, its mathematical CPA is technically undefined or infinite. The script handles this edge case by directly evaluating the total cost against your threshold CPA ceiling (cost = targetCpa 2.5), ensuring that zero-conversion budget drains are flagged immediately.