GAQL Script: Exclude Surging High CPC Zero Conversion Queries
Build a custom GAQL script for Google Ads to detect surging CPC search terms with zero conversions and automatically add negative keywords to save ad spend.
By AdTurbo Team · 2026-10-15
Every media buyer has experienced the Monday morning dread: opening a Google Ads account to discover that an automated bidding strategy poured hundreds or thousands of dollars into a handful of search queries whose cost-per-click (CPC) suddenly doubled or tripled—without yielding a single order. While automated bidding systems like Maximize Conversions and Target CPA are designed to pursue efficiency, their exploratory learning algorithms can aggressively overbid on low-intent or unproven queries during temporary market fluctuations.
Left unchecked, these runaway queries quietly erode your return on ad spend (ROAS). Manually parsing search term reports once a week is too slow; by the time you spot a query that spiked to a $14 CPC with zero conversions, the budget is already spent.
To solve this, you can build a custom Google Ads Query Language (GAQL) script. By querying Google Ads API resources directly within Google Apps Script, you can programmatically flag search queries whose CPC deviates sharply from your account baseline and automatically exclude them. This guide walks you through building an enterprise-grade GAQL script to automate negative keyword additions for surging, zero-conversion search queries.
---
The Economics of Query Cannibalization: Why Surging CPCs Drain Budgets
Smart Bidding algorithms frequently enter aggressive bidding loops on broad match or close variant search queries. When a query shows an initial micro-signal—such as an engaged session or an assisted conversion—bidding algorithms may bid well above average historical CPCs to win incremental impression share. If that query fails to convert into revenue, the financial penalty can be catastrophic for tight advertising margins.
The Mechanics of Sudden CPC Spikes in Smart Bidding
Modern Google Ads accounts rely heavily on Smart Bidding at auction time. Rather than evaluating a keyword's historical fixed bid, Google evaluates contextual signals (device, location, browsing history, time of day) and adjusts the bid per individual impression. However, this creates three structural vulnerabilities:
1. Close Variant Drift: Google's broad match matching engine frequently maps high-value commercial keywords to distantly related informational queries with high auction competition.
2. Auction Competition Squeezes: If several automated bidding algorithms from competitors enter an auction for the same long-tail variant simultaneously, auction-clearing prices spike exponentially.
3. Attribution Hallucination: Algorithmic models can over-index on historical soft micro-conversions (like button clicks or page scrolls), treating them as high-intent signals and bidding aggressively on queries that never produce actual purchases.
When these factors align, a search term that normally costs $1.80 per click can suddenly clear at $8.50. If the term accumulates 40 clicks over 48 hours without an order, that single rogue query consumes $340 of your daily budget.
The True Cost of Zero-Order Search Terms
Zero-conversion search queries do not merely waste direct ad spend; they inflict opportunity cost across the entire ad group. When your daily campaign budget is capped, every dollar absorbed by an unprofitable, high-CPC search term is a dollar stripped away from your proven, top-performing core keywords.
To understand how to inspect these patterns manually, review our Google Ads search terms report guide. However, manual reviews are inherently reactive. Implementing an automated script allows you to enforce deterministic guardrails around automated bidding algorithms, neutralizing budget bleeds before they distort your monthly metrics.
---
Understanding Google Ads Query Language (GAQL) for Search Terms
Google Ads Query Language (GAQL) is the SQL-like query interface used to extract reporting data and resource metadata from the Google Ads API. For years, Google Ads Scripts used the older AdWords Query Language (AWQL). GAQL replaces AWQL, bringing strict data typing, normalized resource schemas, and structured metric fields.
GAQL vs Old AWQL: Core Differences & Syntax
If you have worked with legacy Google Ads scripts, migrating to GAQL requires understanding several fundamental architectural changes:
• Resource-Centric Architecture: In AWQL, you queried flat reporting tables like SEARCHQUERYPERFORMANCEREPORT. In GAQL, you query unified resources like searchtermview, linking attributes and metrics via nested dot notation (metrics.clicks, searchtermview.searchterm).
• Strict Value Representation: Currency values in GAQL are returned in micros (one million micros equal one unit of currency). An average CPC of $2.50 is returned as 2500000.
• Condition Filtering: GAQL uses explicit filtering operators (=, !=, , <, IN, LIKE, REGEXPMATCH). Unlike SQL, GAQL does not support arbitrary JOIN or GROUP BY operations; the resource itself dictates the grouping level.
Querying the searchtermview Resource
To evaluate search terms, we query the searchtermview. This resource provides historical search term performance aggregated at the ad group level. Here is the foundational GAQL query required to isolate spend, conversion, and CPC metrics:
sql
SELECT
searchtermview.searchterm,
searchtermview.status,
campaign.id,
campaign.name,
adgroup.id,
adgroup.name,
metrics.clicks,
metrics.costmicros,
metrics.conversions,
metrics.averagecpc
FROM searchtermview
WHERE segments.date DURING LAST7DAYS
AND metrics.clicks = 5
AND metrics.conversions = 0
ORDER BY metrics.costmicros DESC
This query forms the diagnostic engine of our automated negative script. It extracts all queries from the last seven days that logged at least 5 clicks, generated zero conversions, and sorts them by total wasted spend.
---
Defining the Detection Logic: Surge Multipliers and Zero-Conversion Thresholds
To prevent our script from indiscriminately excluding normal variations, we must define mathematical thresholds that separate expected CPC fluctuations from true budget-destroying surges.
Baseline Cost per Click vs Surging Window
A static CPC threshold (e.g., "exclude anything over $5") fails because different ad groups and campaigns have naturally different clearing costs. A B2B enterprise software campaign might expect an $18 average CPC, whereas an e-commerce apparel campaign might consider a $3 CPC unacceptable.
Instead, the detection logic must calculate a dynamic Surge Multiplier. We calculate the baseline average CPC for the entire ad group over a stable 30-day lookback window, then compare it to the specific query's average CPC over the last 3 to 7 days.
$\text{Surge Ratio} = \frac{\text{Query Avg CPC (Last 7 Days)}},{\text{Ad Group Baseline Avg CPC (Last 30 Days)}}$
If the query's Surge Ratio exceeds your defined multiplier (typically 1.5x to 2.5x) and the term has generated zero conversions while crossing a minimum spend threshold, the script triggers an exclusion.
+-----------------------------------------------------------------------------------------+
| SURGE DETECTION PIPELINE |
+-----------------------------------------------------------------------------------------+
| 1. Calculate Ad Group Baseline: (30-day Total Spend / 30-day Total Clicks) |
| 2. Pull Search Terms (Last 7 days) via searchtermview |
| 3. Filter: Conversions == 0 AND Clicks = MinClickThreshold |
| 4. Evaluate Condition: |
| - Query Spend = MaxAllowableZeroConversionSpend? |
| OR |
| - (Query CPC / Ad Group Baseline CPC) = SurgeMultiplier? |
| 5. Apply Negative: Add exact match negative keyword to Ad Group or Shared List |
+-----------------------------------------------------------------------------------------+
Setting the Zero-Conversion Spend Threshold
In addition to the Surge Multiplier, establish an absolute spend ceiling based on your target CPA. If your campaign Target CPA is $40, allowing a single non-converting query to accumulate $80 or $100 without a conversion is unacceptable, even if its CPC did not surge dramatically.
A proven rule of thumb:
• Moderate Tolerance: Flag queries with zero conversions when spend reaches $1.5\times$ Target CPA.
• Strict Tolerance: Flag queries with zero conversions when spend reaches $1.0\times$ Target CPA, provided the query's CPC is at least $1.4\times$ higher than the ad group baseline.
If you need comprehensive lists of standard exclusions to run alongside this logic, see our curated repository of negative keywords examples.
---
Complete Production Script: GAQL Query, Parsing, and Automated Negatives
The following Google Ads Script uses the AdsApp.search() GAQL engine to identify high-cost, surging, zero-conversion search terms and automatically exclude them as exact match negative keywords at the ad group level.
Full Google Ads Script Code (GAQL + Apps Script)
javascript
/
• GAQL Surging CPC Zero-Conversion Excluder
• Author: AdTurbo Engineering
• Description: Identifies search terms over the last 7 days with zero conversions
• that exhibit a surging CPC relative to the ad group 30-day baseline, or exceed
• a maximum non-converting spend limit. Automatically adds them as negative keywords.
/
const CONFIG = {
SURGEMULTIPLIER: 1.75, // Query CPC must be 1.75x higher than ad group 30-day average
MINCLICKS: 5, // Minimum clicks on the query in last 7 days to evaluate
MAXZEROCONVSPEND: 50.00, // Absolute spend ceiling in account currency for 0-conv queries
DRYRUN: true, // Set to false to actually apply negative keywords
CAMPAIGNLABEL: '', // Optional: Target specific campaigns by label. Empty string = all active.
NOTIFICATIONEMAIL: '[email protected]' // Email to receive run summary
};
function main() {
Logger.log('Starting GAQL Surging CPC Audit...');
// Step 1: Pre-calculate 30-day baseline CPC for active ad groups
const adGroupBaselines = getAdGroupBaselines();
// Step 2: Query 7-day search term performance via GAQL
const rogueQueries = findRogueQueries(adGroupBaselines);
// Step 3: Process exclusions and send reporting log
processExclusions(rogueQueries);
}
function getAdGroupBaselines() {
const baselines = {};
const query =
SELECT
adgroup.id,
metrics.costmicros,
metrics.clicks
FROM adgroup
WHERE segments.date DURING LAST30DAYS
AND campaign.status = 'ENABLED'
AND adgroup.status = 'ENABLED'
;
const response = AdsApp.search(query);
while (response.hasNext()) {
const row = response.next();
const adGroupId = row.adGroup.id;
const cost = row.metrics.costMicros / 1000000;
const clicks = row.metrics.clicks;
if (clicks 0) {
baselines[adGroupId] = cost / clicks;
} else {
baselines[adGroupId] = 0;
}
}
return baselines;
}
function findRogueQueries(baselines) {
const flagged = [];
let query =
SELECT
searchtermview.searchterm,
adgroup.id,
adgroup.name,
campaign.id,
campaign.name,
metrics.clicks,
metrics.costmicros,
metrics.conversions,
metrics.averagecpc
FROM searchtermview
WHERE segments.date DURING LAST7DAYS
AND metrics.clicks = ${CONFIG.MINCLICKS}
AND metrics.conversions = 0
;
if (CONFIG.CAMPAIGNLABEL !== '') {
query += AND campaign.labels CONTAINS ANY ['${CONFIG.CAMPAIGNLABEL}'];
}
const response = AdsApp.search(query);
while (response.hasNext()) {
const row = response.next();
const adGroupId = row.adGroup.id;
const queryText = row.searchTermView.searchTerm;
const clicks = row.metrics.clicks;
const spend = row.metrics.costMicros / 1000000;
const avgCpc = row.metrics.averageCpc / 1000000;
const baselineCpc = baselines[adGroupId] || 0;
const isSurging = baselineCpc 0 && (avgCpc = baselineCpc CONFIG.SURGEMULTIPLIER);
const exceedsSpendCap = spend = CONFIG.MAXZEROCONVSPEND;
if (isSurging || exceedsSpendCap) {
flagged.push({
adGroupId: adGroupId,
adGroupName: row.adGroup.name,
campaignName: row.campaign.name,
searchTerm: queryText,
clicks: clicks,
spend: spend,
avgCpc: avgCpc,
baselineCpc: baselineCpc,
reason: exceedsSpendCap ? 'Spend Ceiling Exceeded' : 'CPC Surge'
});
}
}
return flagged;
}
function processExclusions(flaggedQueries) {
let logBody = GAQL Exclusion Audit Results - Found ${flaggedQueries.length} rogue queries.\n\n;
for (const item of flaggedQueries) {
const logEntry = [${item.reason}] Campaign: "${item.campaignName}" | AdGroup: "${item.adGroupName}" | +
Query: "${item.searchTerm}" | Spend: ${item.spend.toFixed(2)} | +
Query CPC: ${item.avgCpc.toFixed(2)} (Baseline: ${item.baselineCpc.toFixed(2)});
Logger.log(logEntry);
logBody += logEntry + '\n';
if (!CONFIG.DRYRUN) {
try {
const adGroupIterator = AdsApp.adGroups().withIds([item.adGroupId]).get();
if (adGroupIterator.hasNext()) {
const adGroup = adGroupIterator.next();
// Add as negative exact match to prevent collateral traffic loss
adGroup.createNegativeKeyword([${item.searchTerm}]);
Logger.log(Successfully added negative exact match: [${item.searchTerm}]);
}
} catch (err) {
Logger.log(Error adding negative for "${item.searchTerm}": ${err.message});
}
}
}
if (CONFIG.NOTIFICATIONEMAIL && flaggedQueries.length 0) {
MailApp.sendEmail(
CONFIG.NOTIFICATIONEMAIL,
Google Ads Alert: ${flaggedQueries.length} High-CPC Zero-Conversion Queries Flagged,
logBody
);
}
}
Code Walkthrough and Architecture Breakdown
This script runs in three coordinated phases designed to minimize API quota usage while ensuring rigorous data integrity:
1. Baseline Ingestion (getAdGroupBaselines): Queries the adgroup resource over the prior 30 days. It sums metrics.costmicros and metrics.clicks to calculate the true weighted average CPC for every active ad group. It stores these numbers in a memory hash keyed by adGroup.id.
2. Surge Filtering (findRogueQueries): Fires a targeted GAQL query against searchtermview for the last 7 days. By filtering natively inside GAQL (metrics.clicks = 5 and metrics.conversions = 0), we reduce the payload returned over the wire by over 90%. In memory, it tests whether the query violated the surge multiplier or the hard spend ceiling.
3. Safe Execution (processExclusions): Resolves the parent ad group using standard AdsApp selectors and adds the exact match query string enclosed in square brackets ([search term]). Wrapping the term in brackets ensures you do not inadvertently block legitimate core search queries.
---
Comparison: Script Automation vs Rules vs Modern AI Agents
Advertisers looking to control wasted ad spend generally rely on one of four execution methods: manual search term curation, native Google Ads Automated Rules, custom GAQL scripts, or modern autonomous AI agents. Understanding the trade-offs helps you determine whether custom scripting fits your operational structure.
| Feature / Capability | Manual Review | Google Automated Rules | Custom GAQL Script | Autonomous AI Manager |
| :--- | :--- | :--- | :--- | :--- |
| Detection Latency | 7–30 Days (Lagging) | 24 Hours | 1–24 Hours | Real-Time / Hourly |
| Dynamic Baselines (e.g. Surge %) | Impossible at scale | No (Static thresholds only) | Yes (Calculated via code) | Yes (Machine-learning baselines) |
| Match-Type Granularity | High | Low | High (Enforced exact negatives) | High (Predictive semantic exclusion) |
| Lookback Flexibility | Manual selection | Fixed pre-sets | Fully customizable (3d, 7d, 30d) | Multi-horizon dynamic |
| Maintenance Overhead | High (5+ hrs/week) | Low | Moderate (Script breaks/API updates) | Zero |
| Attribution Lag Compensation | High human error | None (Causes false positives) | Requires custom code buffer | Automated probabilistic modeling |
While Google Ads Automated Rules can execute simple checks (e.g., "Pause keyword if Cost $100 and Conversions = 0"), they cannot compute cross-resource dynamic ratios like query-level versus ad-group-level CPC baselines. A custom GAQL script fills this void effectively.
However, maintaining custom code requires technical oversight. If Google deprecates an API endpoint or changes field naming conventions, custom scripts fail silently unless you actively monitor execution logs. Marketers seeking enterprise-grade oversight without the maintenance burden of custom code often adopt specialized Google Ads automation solutions. Platforms like AdTurbo ($149/mo with a 7-day trial, credit card required) act as continuous autonomous agents, catching runaway spend patterns, cross-checking conversion latency, and reducing wasted budget by typically 15% to 35% without requiring custom API engineering.
---
Safety Guardrails, Whitelisting, and Avoiding False Negatives
Automating negative keywords carries inherent risk: if your logic is too aggressive, you will accidentally exclude valuable search terms that simply required a longer purchase consideration cycle. Implementing protective guardrails is non-negotiable.
Attribution Lag and Conversion Delay Buffer
One of the most dangerous traps in automated negative scripts is conversion lag. For high-consideration products or B2B sales cycles, a customer may click an ad on Monday but complete the purchase or lead form on Friday via direct traffic or an attribution-credited visit.
If your script queries LAST7DAYS on Wednesday morning, Monday's high-CPC click appears to have zero conversions. If the script excludes that query immediately, you shut off profitable acquisition paths before Google's data-driven attribution window completes.
+-----------------------------------------------------------------------------+
| CONVERSION LAG TIMELINE BUFFER |
+-----------------------------------------------------------------------------+
| Day 0 (Click Occurs) ---- Day 1 to 2 (Consideration) ---- Day 3 (Purchase) |
| [Script Safe Zone: Exclude] |
| <------------------------- |
| Buffer Window: 48h |
+-----------------------------------------------------------------------------+
To prevent this, enforce a 48-hour attribution buffer in your GAQL date segment. Instead of querying DURING LAST7DAYS, construct a custom date range using JavaScript date objects that evaluates Days -9 through -2 relative to today. This allows 48 hours for early conversion data to populate.
Whitelisting Brand and High-Intent Product Names
Never deploy a negative keyword script without an exclusion whitelist. If your brand term experiences a temporary surge in traffic (such as during a PR campaign or product launch), CPCs may fluctuate. If the script adds your own brand name or primary SKU numbers as negative keywords, your core campaigns will drop in impression share immediately.
Incorporate regex-based whitelisting directly into your parsing loop:
javascript
const BRANDWHITELIST = ['acme', 'acme pro', 'acme widget', 'order'];
function isWhitelisted(searchTerm) {
const normalized = searchTerm.toLowerCase();
return BRANDWHITELIST.some(brand = normalized.includes(brand));
}
// Inside findRogueQueries loop:
if (isWhitelisted(queryText)) {
Logger.log(Skipping whitelisted search term: ${queryText});
continue;
}
To expand your understanding of query hygiene and auditing workflows, read through our detailed guide on how to find negative keywords.
Script Execution Limits and Quota Management
Google Ads Scripts operate under strict Google Apps Script runtime quotas:
• Execution Time Limit: Standard Google Ads scripts terminate automatically after 30 minutes. If your account contains millions of search terms, a non-indexed GAQL query will time out.
• Memory Constraints: Large arrays in Apps Script will throw Out of Memory errors. Always apply restrictive filtering directly within your GAQL WHERE clause (such as metrics.clicks = 5) rather than pulling thousands of zero-click queries into memory to filter in JavaScript.
• Batch Limit for Mutations: When adding negative keywords, avoid firing individual network calls sequentially for hundreds of items. Keep your daily exclusion counts reasonable by tuning the SURGEMULTIPLIER and MINCLICKS parameters.
---
Step-by-Step Implementation and Deployment in Google Ads Scripts
Deploying your GAQL script requires entering the Google Ads internal scripting environment and configuring execution triggers.
Creating the Script in Google Ads UI
1. Log in to your Google Ads account.
2. In the top navigation bar, navigate to Tools and Settings (wrench icon) Bulk Actions Scripts.
3. Click the blue + button to create a new script.
4. Clear all placeholder code from the editor window.
5. Copy the production script code provided in Section 4 and paste it into the editor.
6. Name the script [AdTurbo] Surging CPC Zero-Conversion Excluder.
+-----------------------------------------------------------------------------+
| GOOGLE ADS SCRIPT SETUP FLOW |
+-----------------------------------------------------------------------------+
| 1. Tools & Settings - Bulk Actions - Scripts |
| 2. Create Script - Paste Code |
| 3. Click 'Authorize' - Grant Google Account Permissions |
| 4. Run 'Preview' (DRYRUN = true) - Inspect Execution Logs |
| 5. Switch DRYRUN = false - Save - Set Frequency Schedule |
+-----------------------------------------------------------------------------+
Setting Authorization and Scheduling Triggers
Before a script can read performance reports or apply negative keywords, you must authorize it to act on your behalf:
1. Click the Authorize button located at the bottom right of the script workspace.
2. Select your Google account and click Allow when prompted for Google Ads API access permissions.
3. Keep DRYRUN: true during your initial test. Click Preview.
4. Review the Logs tab at the bottom of the screen. Ensure the script correctly calculates ad group baseline CPCs and flags only rogue queries without throwing syntax or timeout errors.
5. Once satisfied with the logged exclusions, toggle DRYRUN: false in the CONFIG object.
6. Save the script, return to the main Scripts dashboard, and set the Frequency trigger to Weekly (e.g., every Monday at 3:00 AM) or Daily depending on your daily spend volume.
For enterprise accounts with complex multi-campaign hierarchies, integrating this with broader auditing routines ensures complete account health. Check out our comprehensive PPC audit checklist for a complete overview of structural account health checks.
---
Advanced Extension: Exporting Flagged Queries to Google Sheets for One-Click Human Review
If your organization requires human sign-off before negative keywords are pushed live, you can modify the script to stream flagged queries directly to a Google Sheet instead of mutating the ad group directly. This provides a human-in-the-loop workflow without sacrificing automation speed.
Google Sheets Integration Snippet
Replace the processExclusions function with this spreadsheet logging mechanism:
javascript
const SPREADSHEETURL = 'https://docs.google.com/spreadsheets/d/YOURSHEETIDHERE/edit';
function logToGoogleSheet(flaggedQueries) {
const sheet = SpreadsheetApp.openByUrl(SPREADSHEETURL).getActiveSheet();
// Write header if sheet is empty
if (sheet.getLastRow() === 0) {
sheet.appendRow([
'Timestamp', 'Reason', 'Campaign', 'Ad Group', 'Search Term',
'Spend', 'Query CPC', 'Baseline CPC', 'Clicks', 'Status'
]);
sheet.getRange(1, 1, 1, 10).setFontWeight('bold');
}
const timestamp = new Date().toISOString().slice(0, 10);
const rows = [];
for (const item of flaggedQueries) {
rows.push([
timestamp,
item.reason,
item.campaignName,
item.adGroupName,
item.searchTerm,
item.spend.toFixed(2),
item.avgCpc.toFixed(2),
item.baselineCpc.toFixed(2),
item.clicks,
'PENDINGAPPROVAL'
]);
}
if (rows.length 0) {
sheet.getRange(sheet.getLastRow() + 1, 1, rows.length, 10).setValues(rows);
Logger.log(Successfully logged ${rows.length} queries to Google Sheets.);
}
}
Using this staging architecture, your media buyers can review flagged terms in the sheet, change the PENDINGAPPROVAL status to APPROVED, and use a secondary Google Apps Script to read the approved rows and execute the negative keyword additions via the Google Ads API. For teams managing multiple high-spend brands, delegating this detection work to modern PPC management software can provide this level of oversight natively without maintaining separate Google Sheets and Google Apps Script triggers.
---
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
How often should I run a GAQL negative keyword script?
For accounts spending under $15,000 per month, running the script once a week is generally optimal to avoid premature exclusions caused by low statistical sample sizes. For accounts spending over $50,000 per month, running the script daily with a built-in 48-hour attribution buffer allows you to catch expensive surging terms before they consume substantial daily budget.
Will this script add broad match or exact match negative keywords?
The production script provided above adds negative keywords exclusively in exact match format (enclosing the string in square brackets [like this]). Using exact match negative exclusions prevents inadvertent traffic cannibalization, ensuring you block the exact wasteful phrase without shutting off related, converting search queries.
Why does the script compare query CPC to the ad group baseline instead of campaign baseline?
Ad groups within the same campaign often target distinct keyword clusters with wildly different auction dynamics, search intents, and historical clearing CPCs. Calculating the baseline at the ad group level provides a much tighter, more accurate statistical baseline, minimizing false positives in ad groups that naturally carry higher competitive bids.
Where can I find documentation for Google Apps Script in Google Ads?
Google maintains dedicated developer documentation within the Google Developers portal under the Google Ads Scripts guides section. You can find reference documentation for all GAQL-supported resources, code samples for automated bidding integrations, and API quota limits directly in the Google Ads Scripts API reference guide.