Second Query

Free Google Ads scripts

Three scripts I'd want running in any account. Each one reads your account data, makes no changes to campaigns, bids or budgets, and writes its results to a tidy Google Sheet or a short email. Copy the code, change a setting or two, and you're done. No sign-up, and you're free to adapt them.

Adding a script takes about two minutes

  1. Open scripts. In Google Ads, go to Tools, then Bulk actions, then Scripts, and click the blue plus.
  2. Paste the code. Delete the placeholder, paste the script and give it a name.
  3. Change the settings. They're at the top, in plain English: an email address, a budget or a date range.
  4. Preview, then run. Authorise it when asked, click Preview to check the log, then Run. Set a schedule if the script suggests one.
Weekly

Search term n‑gram analyser

Find the words that waste money and the ones that convert, across thousands of search terms at once.

Download

What it does

Splits every search term from your Search campaigns into single words, two-word phrases and three-word phrases, then adds up impressions, clicks, cost and conversions for each one.

What you get

  • A Summary tab with the headline numbers and a chart of the costliest phrases that haven't converted.
  • A tab for each n-gram length, sorted by cost, with filters on.
  • Pink flags where a phrase has spent at least twice your average cost per conversion without converting, and green flags for phrases converting at 80% or less of your average cost per conversion.

Settings worth knowing

  • LOOKBACK_DAYS: 30 by default. Use 90 for smaller accounts.
  • WASTE_MIN_COST: set your own threshold if you'd rather not use twice your average cost per conversion.
  • CAMPAIGN_NAME_CONTAINS: limit it to non-brand campaigns, for example.
Show the code
/**
 * Search term n-gram analyser
 * A free Google Ads script from Second Query: https://secondquery.com/google-ads-scripts/
 * Version 1.0, November 2026. Free to use and adapt; please keep this header.
 *
 * WHAT IT DOES
 * Splits every search term from your Search campaigns into single words, two-word phrases
 * and three-word phrases ("n-grams"), adds up impressions, clicks, cost and conversions for
 * each one, and writes the results to a Google Sheet. The Summary tab shows the totals and a
 * chart of the costliest phrases that haven't converted, which are usually your best
 * negative keyword themes. The other tabs list every n-gram so you can sort and filter.
 *
 * It only reads data. It never changes anything in your account.
 *
 * HOW TO USE IT
 * 1. In Google Ads, go to Tools > Bulk actions > Scripts, click +, and paste this in.
 * 2. Leave SPREADSHEET_URL blank for the first run. The script creates a Sheet and logs its link.
 * 3. Click Preview to check it, then Run. Paste the Sheet's link into SPREADSHEET_URL to reuse it.
 * 4. Optional: schedule it weekly.
 */

// ---- Settings -------------------------------------------------------------------------
var SPREADSHEET_URL = '';          // Blank = create a new Sheet. Paste a Sheet URL here to reuse it.
var LOOKBACK_DAYS = 30;            // Days of search terms to analyse, ending yesterday.
var MIN_IMPRESSIONS = 1;           // Leave out n-grams with fewer impressions than this.
var WASTE_MIN_COST = 0;            // Flag n-grams with no conversions once cost reaches this.
                                   // 0 = use twice your average cost per conversion.
var CAMPAIGN_NAME_CONTAINS = '';   // Only include campaigns whose name contains this. Blank = all.
var EMAIL = '';                    // Optional: email the Sheet link when the run finishes.
// ----------------------------------------------------------------------------------------

var BRAND = { ink: '#06222e', pink: '#ff2e7e', soft: '#eaf6fa', rule: '#b2d3dd', white: '#ffffff' };
var TABS = [
  { n: 1, name: 'Single words' },
  { n: 2, name: 'Two-word phrases' },
  { n: 3, name: 'Three-word phrases' }
];

function main() {
  var account = AdsApp.currentAccount();
  var tz = account.getTimeZone();
  var currency = account.getCurrencyCode();
  var range = dateRange_(LOOKBACK_DAYS, tz);

  var terms = fetchSearchTerms_(range);
  if (!terms.length) {
    Logger.log('No search terms found between ' + range.from + ' and ' + range.to + '. Nothing to write.');
    return;
  }

  var totals = sum_(terms);
  var avgCpa = totals.conversions > 0 ? totals.cost / totals.conversions : 0;
  var wasteAt = WASTE_MIN_COST > 0 ? WASTE_MIN_COST : 2 * avgCpa;

  var ss = openSpreadsheet_(account.getName());
  var summaryRows = [];
  TABS.forEach(function (tab) {
    var grams = buildNgrams_(terms, tab.n);
    grams.forEach(function (g) { g.flag = flag_(g, wasteAt, avgCpa); });
    writeGramTab_(ss, tab.name, grams, currency);
    summaryRows.push({ tab: tab, grams: grams });
  });
  writeSummary_(ss, account.getName(), range, currency, totals, avgCpa, wasteAt, summaryRows);

  var url = ss.getUrl();
  Logger.log('Done. ' + terms.length + ' search terms analysed. Sheet: ' + url);
  if (EMAIL) {
    MailApp.sendEmail(EMAIL, 'Search term n-grams: ' + account.getName(),
      'Your n-gram analysis for ' + range.from + ' to ' + range.to + ' is ready:\n' + url +
      '\n\nFrom the free Second Query n-gram script: https://secondquery.com/google-ads-scripts/');
  }
}

// Search terms from Search campaigns, rolled up by term.
function fetchSearchTerms_(range) {
  var query =
    'SELECT campaign.name, search_term_view.search_term, metrics.impressions, metrics.clicks, ' +
    'metrics.cost_micros, metrics.conversions, metrics.conversions_value ' +
    'FROM search_term_view ' +
    "WHERE segments.date BETWEEN '" + range.from + "' AND '" + range.to + "' " +
    "AND campaign.advertising_channel_type = 'SEARCH' AND metrics.impressions > 0";
  var rows = AdsApp.search(query);
  var byTerm = {};
  var filter = CAMPAIGN_NAME_CONTAINS.toLowerCase();
  while (rows.hasNext()) {
    var row = rows.next();
    if (filter && String(row.campaign.name).toLowerCase().indexOf(filter) < 0) continue;
    var term = String(row.searchTermView.searchTerm || '').trim();
    if (!term) continue;
    var m = row.metrics;
    var t = byTerm[term] || (byTerm[term] = { term: term, impressions: 0, clicks: 0, cost: 0, conversions: 0, value: 0 });
    t.impressions += num_(m.impressions);
    t.clicks += num_(m.clicks);
    t.cost += num_(m.costMicros) / 1e6;
    t.conversions += num_(m.conversions);
    t.value += num_(m.conversionsValue);
  }
  return Object.keys(byTerm).map(function (k) { return byTerm[k]; });
}

// Each n-gram counts once per search term, so repeated words don't double count.
function buildNgrams_(terms, n) {
  var map = {};
  terms.forEach(function (t) {
    var words = t.term.toLowerCase().replace(/["“”(),.!?;:|\/]+/g, ' ').split(/\s+/).filter(function (w) { return w; });
    var seen = {};
    for (var i = 0; i + n <= words.length; i++) {
      var gram = words.slice(i, i + n).join(' ');
      if (seen[gram]) continue;
      seen[gram] = true;
      var g = map[gram] || (map[gram] = { gram: gram, terms: 0, impressions: 0, clicks: 0, cost: 0, conversions: 0, value: 0 });
      g.terms += 1;
      g.impressions += t.impressions;
      g.clicks += t.clicks;
      g.cost += t.cost;
      g.conversions += t.conversions;
      g.value += t.value;
    }
  });
  return Object.keys(map)
    .map(function (k) { return map[k]; })
    .filter(function (g) { return g.impressions >= MIN_IMPRESSIONS; })
    .sort(function (a, b) { return b.cost - a.cost; });
}

function flag_(g, wasteAt, avgCpa) {
  if (g.conversions === 0 && wasteAt > 0 && g.cost >= wasteAt) return 'No conversions, high cost';
  if (g.conversions > 0 && avgCpa > 0 && g.cost / g.conversions <= 0.8 * avgCpa) return 'Converts well';
  return '';
}

function writeGramTab_(ss, name, grams, currency) {
  var sh = resetSheet_(ss, name);
  var head = ['N-gram', 'Search terms', 'Impressions', 'Clicks', 'CTR', 'Cost (' + currency + ')', 'Conversions',
    'Conv. rate', 'Cost / conv.', 'Conv. value', 'Value / cost', 'Flag'];
  var data = grams.map(function (g) {
    return [g.gram, g.terms, g.impressions, g.clicks, div_(g.clicks, g.impressions), round_(g.cost), round_(g.conversions),
      div_(g.conversions, g.clicks), g.conversions ? round_(g.cost / g.conversions) : '', round_(g.value),
      g.cost ? round_(g.value / g.cost) : '', g.flag];
  });
  sh.getRange(1, 1, 1, head.length).setValues([head]);
  if (data.length) sh.getRange(2, 1, data.length, head.length).setValues(data);
  styleTable_(sh, head.length, data.length);
  if (data.length) {
    sh.getRange(2, 5, data.length, 1).setNumberFormat('0.0%');
    sh.getRange(2, 8, data.length, 1).setNumberFormat('0.0%');
    sh.getRange(2, 6, data.length, 1).setNumberFormat('#,##0.00');
    sh.getRange(2, 9, data.length, 3).setNumberFormat('#,##0.00');
    var rules = sh.getConditionalFormatRules();
    rules.push(SpreadsheetApp.newConditionalFormatRule().whenTextEqualTo('No conversions, high cost')
      .setBackground('#ffe3ee').setFontColor('#c20a52').setRanges([sh.getRange(2, 12, data.length, 1)]).build());
    rules.push(SpreadsheetApp.newConditionalFormatRule().whenTextEqualTo('Converts well')
      .setBackground('#e2f5ea').setFontColor('#1d6b3f').setRanges([sh.getRange(2, 12, data.length, 1)]).build());
    sh.setConditionalFormatRules(rules);
    sh.getRange(1, 1, data.length + 1, head.length).createFilter();
  }
  sh.setColumnWidth(1, 240);
  sh.setColumnWidth(12, 190);
}

function writeSummary_(ss, accountName, range, currency, totals, avgCpa, wasteAt, tabs) {
  var sh = resetSheet_(ss, 'Summary');
  ss.setActiveSheet(sh);
  ss.moveActiveSheet(1);
  sh.getRange('A1').setValue('Search term n-grams').setFontSize(20).setFontWeight('bold').setFontColor(BRAND.ink);
  sh.getRange('A2').setValue(accountName + '  ·  ' + range.from + ' to ' + range.to + '  ·  Search campaigns' +
    (CAMPAIGN_NAME_CONTAINS ? ' containing "' + CAMPAIGN_NAME_CONTAINS + '"' : '')).setFontColor('#3a5763');

  var kpis = [
    ['Cost (' + currency + ')', round_(totals.cost)],
    ['Clicks', totals.clicks],
    ['Conversions', round_(totals.conversions)],
    ['Average cost / conv.', avgCpa ? round_(avgCpa) : 'n/a'],
    ['Waste threshold', wasteAt ? round_(wasteAt) : 'n/a']
  ];
  sh.getRange(4, 1, 1, kpis.length).setValues([kpis.map(function (k) { return k[0]; })])
    .setFontColor('#3a5763').setFontSize(9);
  sh.getRange(5, 1, 1, kpis.length).setValues([kpis.map(function (k) { return k[1]; })])
    .setFontSize(16).setFontWeight('bold').setFontColor(BRAND.ink).setNumberFormat('#,##0.##');

  // Wasted-spend table across all three tabs, then a chart of the top single words and phrases.
  var row = 8;
  sh.getRange(row, 1).setValue('Costliest n-grams with no conversions').setFontWeight('bold').setFontSize(13).setFontColor(BRAND.ink);
  var head = ['N-gram', 'Type', 'Cost (' + currency + ')', 'Clicks', 'Search terms'];
  var wasted = [];
  tabs.forEach(function (t) {
    t.grams.filter(function (g) { return g.flag === 'No conversions, high cost'; }).slice(0, 10).forEach(function (g) {
      wasted.push([g.gram, t.tab.name, round_(g.cost), g.clicks, g.terms]);
    });
  });
  wasted.sort(function (a, b) { return b[2] - a[2]; });
  wasted = wasted.slice(0, 15);
  sh.getRange(row + 1, 1, 1, head.length).setValues([head]);
  if (wasted.length) {
    sh.getRange(row + 2, 1, wasted.length, head.length).setValues(wasted);
    sh.getRange(row + 2, 3, wasted.length, 1).setNumberFormat('#,##0.00');
  } else {
    sh.getRange(row + 2, 1).setValue(wasteAt ? 'Nothing over the waste threshold. Nice.' : 'No conversions recorded, so set WASTE_MIN_COST to flag waste.');
  }
  styleHeader_(sh.getRange(row + 1, 1, 1, head.length));
  bands_(sh, row + 2, head.length, Math.max(wasted.length, 1));

  if (wasted.length) {
    var chart = sh.newChart().asBarChart()
      .addRange(sh.getRange(row + 1, 1, wasted.length + 1, 1))
      .addRange(sh.getRange(row + 1, 3, wasted.length + 1, 1))
      .setNumHeaders(1)
      .setTitle('No-conversion spend by n-gram')
      .setColors([BRAND.pink])
      .setOption('legend', { position: 'none' })
      .setOption('hAxis.format', '#,##0')
      .setPosition(8, 7, 0, 0)
      .setOption('width', 560)
      .setOption('height', Math.max(260, wasted.length * 28 + 80))
      .build();
    sh.insertChart(chart);
  }

  var notes = row + 4 + Math.max(wasted.length, 1);
  sh.getRange(notes, 1).setValue('How to read this').setFontWeight('bold').setFontColor(BRAND.ink);
  sh.getRange(notes + 1, 1, 3, 1).setValues([
    ['Pink rows have spent at least the waste threshold without a conversion: check the search terms behind them before adding negatives.'],
    ['Green rows convert at 80% or less of your average cost per conversion: candidates for their own keywords or more budget.'],
    ['Each n-gram counts once per search term, so totals across rows add up to more than the account total.']
  ]).setFontColor('#3a5763');
  sh.getRange(notes + 5, 1).setValue('Free script from Second Query · secondquery.com/google-ads-scripts')
    .setFontColor(BRAND.pink).setFontSize(9);
  sh.setColumnWidth(1, 220);
  sh.setColumnWidth(2, 150);
  sh.setHiddenGridlines(true);
}

// ---- Helpers -----------------------------------------------------------------------------
function openSpreadsheet_(accountName) {
  if (SPREADSHEET_URL) return SpreadsheetApp.openByUrl(SPREADSHEET_URL);
  var ss = SpreadsheetApp.create('Search term n-grams: ' + accountName);
  Logger.log('Created a new Sheet. Paste this into SPREADSHEET_URL to reuse it: ' + ss.getUrl());
  return ss;
}

function resetSheet_(ss, name) {
  var sh = ss.getSheetByName(name);
  if (sh) {
    sh.getCharts().forEach(function (c) { sh.removeChart(c); });
    if (sh.getFilter()) sh.getFilter().remove();
    sh.clear();
    sh.clearConditionalFormatRules();
  } else {
    sh = ss.insertSheet(name);
  }
  var blank = ss.getSheetByName('Sheet1');
  if (blank && ss.getSheets().length > 1 && blank.getLastRow() === 0) ss.deleteSheet(blank);
  return sh;
}

function styleTable_(sh, cols, rows) {
  styleHeader_(sh.getRange(1, 1, 1, cols));
  sh.setFrozenRows(1);
  sh.setFrozenColumns(1);
  if (rows) bands_(sh, 2, cols, rows);
}

function styleHeader_(range) {
  range.setBackground(BRAND.ink).setFontColor(BRAND.white).setFontWeight('bold').setWrap(true);
}

function bands_(sh, startRow, cols, rows) {
  var colours = [];
  for (var i = 0; i < rows; i++) {
    var c = i % 2 ? BRAND.soft : BRAND.white;
    var line = [];
    for (var j = 0; j < cols; j++) line.push(c);
    colours.push(line);
  }
  sh.getRange(startRow, 1, rows, cols).setBackgrounds(colours);
}

function dateRange_(days, tz) {
  var end = new Date(Date.now() - 864e5);
  var start = new Date(end.getTime() - (days - 1) * 864e5);
  return { from: Utilities.formatDate(start, tz, 'yyyy-MM-dd'), to: Utilities.formatDate(end, tz, 'yyyy-MM-dd') };
}

function sum_(rows) {
  return rows.reduce(function (a, r) {
    a.impressions += r.impressions; a.clicks += r.clicks; a.cost += r.cost; a.conversions += r.conversions; a.value += r.value;
    return a;
  }, { impressions: 0, clicks: 0, cost: 0, conversions: 0, value: 0 });
}

function num_(v) { var n = Number(v); return isFinite(n) ? n : 0; }
function div_(a, b) { return b ? a / b : 0; }
function round_(v) { return Math.round(v * 100) / 100; }
Daily

Performance anomaly alert

An email the morning after something unusual happens, and silence when nothing does.

Download

What it does

Compares yesterday with the same weekday over the previous four weeks, for the account and for each campaign, so normal weekend dips don't set it off.

What it flags

  • Cost or clicks up or down by more than 40%.
  • Conversions down or up by more than 50%, and cost per conversion moving by more than 50%.
  • A campaign that normally spends and spent nothing.
  • A day that spent more than a normal cost per conversion with no conversions at all.

Settings worth knowing

  • EMAIL: who gets the alert. Separate several addresses with commas.
  • THRESHOLDS: tighten or loosen each one.
  • MIN_BASELINE_CLICKS: stops tiny campaigns raising false alarms.
Show the code
/**
 * Performance anomaly alert
 * A free Google Ads script from Second Query: https://secondquery.com/google-ads-scripts/
 * Version 1.0, November 2026. Free to use and adapt; please keep this header.
 *
 * WHAT IT DOES
 * Every morning, compares yesterday with the same weekday over the previous few weeks, for
 * the account and for each campaign. If cost, clicks, conversions or cost per conversion
 * moved further than your thresholds, or a campaign that normally spends stopped spending,
 * it emails you a short table of what changed. Comparing like-for-like weekdays avoids false
 * alarms from normal weekend dips.
 *
 * It only reads data. It never changes anything in your account. No email means nothing
 * unusual happened.
 *
 * HOW TO USE IT
 * 1. In Google Ads, go to Tools > Bulk actions > Scripts, click +, and paste this in.
 * 2. Put your email address in EMAIL. Click Preview, then Run.
 * 3. Schedule it daily, early in the morning (for example 6am).
 */

// ---- Settings -------------------------------------------------------------------------
var EMAIL = 'you@example.com';      // One address, or several separated by commas.
var WEEKS_TO_COMPARE = 4;           // How many previous same weekdays make the baseline.
var MIN_BASELINE_CLICKS = 20;       // Only check campaigns averaging at least this many clicks.
var THRESHOLDS = {                  // Alert when yesterday moves more than this from the baseline.
  cost: 0.40,                       // 0.40 = 40% up or down
  clicks: 0.40,
  conversions: 0.50,
  costPerConv: 0.50
};
var MIN_BASELINE_CONVERSIONS = 3;   // Only judge conversions and cost / conv. above this baseline.
var CAMPAIGN_NAME_CONTAINS = '';    // Only include campaigns whose name contains this. Blank = all.
// ----------------------------------------------------------------------------------------

function main() {
  var account = AdsApp.currentAccount();
  var tz = account.getTimeZone();
  var currency = account.getCurrencyCode();
  var yesterday = Utilities.formatDate(new Date(Date.now() - 864e5), tz, 'yyyy-MM-dd');
  var baseDays = [];
  for (var w = 1; w <= WEEKS_TO_COMPARE; w++) {
    baseDays.push(Utilities.formatDate(new Date(Date.now() - (1 + 7 * w) * 864e5), tz, 'yyyy-MM-dd'));
  }
  var from = baseDays[baseDays.length - 1];

  var data = fetchDaily_(from, yesterday);
  var findings = [];
  Object.keys(data).forEach(function (id) {
    var c = data[id];
    var check = compare_(c.name, c.days, yesterday, baseDays);
    if (check) findings.push(check);
  });
  var total = compare_('Whole account', totalDays_(data), yesterday, baseDays);
  if (total) findings.unshift(total);

  if (!findings.length) {
    Logger.log('Nothing unusual on ' + yesterday + ' against the last ' + WEEKS_TO_COMPARE + ' same weekdays.');
    return;
  }
  var weekday = Utilities.formatDate(new Date(Date.now() - 864e5), tz, 'EEEE');
  var subject = 'Google Ads: ' + findings.length + ' thing' + (findings.length > 1 ? 's' : '') +
    ' to check in ' + account.getName() + ' (' + yesterday + ')';
  MailApp.sendEmail({ to: EMAIL, subject: subject, htmlBody: emailHtml_(account.getName(), weekday, yesterday, currency, findings) });
  Logger.log('Sent an alert with ' + findings.length + ' finding(s) to ' + EMAIL);
}

function fetchDaily_(from, to) {
  var query =
    'SELECT campaign.id, campaign.name, segments.date, metrics.cost_micros, metrics.clicks, metrics.conversions ' +
    'FROM campaign ' +
    "WHERE segments.date BETWEEN '" + from + "' AND '" + to + "' AND campaign.status != 'REMOVED'";
  var rows = AdsApp.search(query);
  var out = {};
  var filter = CAMPAIGN_NAME_CONTAINS.toLowerCase();
  while (rows.hasNext()) {
    var r = rows.next();
    var name = String(r.campaign.name);
    if (filter && name.toLowerCase().indexOf(filter) < 0) continue;
    var id = String(r.campaign.id);
    var c = out[id] || (out[id] = { name: name, days: {} });
    var d = c.days[r.segments.date] || (c.days[r.segments.date] = { cost: 0, clicks: 0, conversions: 0 });
    d.cost += num_(r.metrics.costMicros) / 1e6;
    d.clicks += num_(r.metrics.clicks);
    d.conversions += num_(r.metrics.conversions);
  }
  return out;
}

function totalDays_(data) {
  var days = {};
  Object.keys(data).forEach(function (id) {
    var c = data[id];
    Object.keys(c.days).forEach(function (date) {
      var t = days[date] || (days[date] = { cost: 0, clicks: 0, conversions: 0 });
      t.cost += c.days[date].cost;
      t.clicks += c.days[date].clicks;
      t.conversions += c.days[date].conversions;
    });
  });
  return days;
}

// Returns a finding when yesterday is outside the thresholds, otherwise null.
function compare_(name, days, yesterday, baseDays) {
  var y = days[yesterday] || { cost: 0, clicks: 0, conversions: 0 };
  var base = { cost: 0, clicks: 0, conversions: 0 };
  baseDays.forEach(function (d) {
    var v = days[d] || { cost: 0, clicks: 0, conversions: 0 };
    base.cost += v.cost / baseDays.length;
    base.clicks += v.clicks / baseDays.length;
    base.conversions += v.conversions / baseDays.length;
  });
  if (base.clicks < MIN_BASELINE_CLICKS) return null;

  var issues = [];
  if (base.cost > 0 && y.cost === 0) {
    issues.push({ metric: 'Cost', note: 'Stopped spending', y: 0, base: base.cost, change: -1 });
  } else {
    pushIfMoved_(issues, 'Cost', y.cost, base.cost, THRESHOLDS.cost);
    pushIfMoved_(issues, 'Clicks', y.clicks, base.clicks, THRESHOLDS.clicks);
  }
  if (base.conversions >= MIN_BASELINE_CONVERSIONS) {
    pushIfMoved_(issues, 'Conversions', y.conversions, base.conversions, THRESHOLDS.conversions);
    var yCpa = y.conversions ? y.cost / y.conversions : null;
    var bCpa = base.cost / base.conversions;
    if (yCpa === null && y.cost > bCpa) {
      issues.push({ metric: 'Cost / conv.', note: 'Spent more than a normal cost per conversion with no conversions', y: y.cost, base: bCpa, change: null });
    } else if (yCpa !== null) {
      pushIfMoved_(issues, 'Cost / conv.', yCpa, bCpa, THRESHOLDS.costPerConv);
    }
  }
  return issues.length ? { name: name, issues: issues } : null;
}

function pushIfMoved_(issues, metric, y, base, limit) {
  if (base <= 0) return;
  var change = (y - base) / base;
  if (Math.abs(change) > limit) issues.push({ metric: metric, note: change > 0 ? 'Up' : 'Down', y: y, base: base, change: change });
}

function emailHtml_(accountName, weekday, date, currency, findings) {
  var cell = 'padding:8px 10px;border-bottom:1px solid #b2d3dd;text-align:left;font:14px Arial,sans-serif;color:#06222e';
  var rows = '';
  findings.forEach(function (f) {
    f.issues.forEach(function (i, n) {
      var money = /Cost/.test(i.metric);
      var fmt = function (v) { return (money ? currency + ' ' : '') + (Math.round(v * 100) / 100).toLocaleString('en-GB'); };
      var pct = i.change === null ? '' : (i.change > 0 ? '+' : '') + Math.round(i.change * 100) + '%';
      var bad = i.change === null || i.metric === 'Cost' || (i.metric === 'Cost / conv.' ? i.change > 0 : i.change < 0);
      var colour = bad ? '#c20a52' : '#1d6b3f';
      rows += '<tr><td style="' + cell + ';font-weight:bold">' + (n === 0 ? esc_(f.name) : '') + '</td>' +
        '<td style="' + cell + '">' + i.metric + '</td>' +
        '<td style="' + cell + '">' + fmt(i.y) + '</td>' +
        '<td style="' + cell + '">' + fmt(i.base) + '</td>' +
        '<td style="' + cell + ';color:' + colour + ';font-weight:bold">' +
        [pct, /^(Up|Down)$/.test(i.note) ? '' : esc_(i.note)].filter(String).join(' · ') + '</td></tr>';
    });
  });
  var th = 'padding:8px 10px;background:#06222e;color:#ffffff;text-align:left;font:bold 13px Arial,sans-serif';
  return '<div style="font:15px Arial,sans-serif;color:#06222e;max-width:720px">' +
    '<p style="font-size:18px;font-weight:bold;margin:0 0 6px">' + esc_(accountName) + ': ' + date + '</p>' +
    '<p style="margin:0 0 14px;color:#3a5763">Yesterday compared with the average of the previous ' + WEEKS_TO_COMPARE + ' ' + weekday + 's.</p>' +
    '<table style="border-collapse:collapse;width:100%"><tr><th style="' + th + '">Campaign</th><th style="' + th + '">Metric</th>' +
    '<th style="' + th + '">Yesterday</th><th style="' + th + '">Usual ' + weekday + '</th><th style="' + th + '">Change</th></tr>' + rows + '</table>' +
    '<p style="margin:16px 0 0;color:#3a5763;font-size:13px">Check recent changes, budgets, disapprovals and conversion tracking first. ' +
    'Free script from <a href="https://secondquery.com/google-ads-scripts/" style="color:#ff2e7e">Second Query</a>.</p></div>';
}

function esc_(s) { return String(s).replace(/[&<>"]/g, function (c) { return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]; }); }
function num_(v) { var n = Number(v); return isFinite(n) ? n : 0; }
Daily

Monthly budget pacing monitor

Know by the 10th whether the month will land on budget, not on the 30th.

Download

What it does

Tracks spend this month against your monthly budget. It works out where you should be by now, the run rate over the last seven days, the projected month-end spend and the daily spend needed to land on budget.

What you get

  • A Google Sheet with the headline numbers, a chart of actual against ideal spend, and a table by campaign.
  • An email if the month is heading more than 10% over or under budget.

Settings worth knowing

  • MONTHLY_BUDGET: in your account's currency.
  • TOLERANCE: 0.10 means an email when the projection is more than 10% out.
  • CAMPAIGN_NAME_CONTAINS: pace one group of campaigns against its own budget.
Show the code
/**
 * Monthly budget pacing monitor
 * A free Google Ads script from Second Query: https://secondquery.com/google-ads-scripts/
 * Version 1.0, November 2026. Free to use and adapt; please keep this header.
 *
 * WHAT IT DOES
 * Tracks spend this month against your monthly budget. It works out spend to date, where you
 * should be by now, the run rate over the last seven days, the projected month-end spend and
 * the daily spend needed to land on budget. It writes this to a Google Sheet with a chart of
 * actual against ideal spend and a table by campaign, and emails you if the month is heading
 * over or under budget by more than your tolerance.
 *
 * It only reads data. It never changes budgets or anything else in your account.
 *
 * HOW TO USE IT
 * 1. In Google Ads, go to Tools > Bulk actions > Scripts, click +, and paste this in.
 * 2. Set MONTHLY_BUDGET (in your account currency) and, if you like, EMAIL.
 * 3. Leave SPREADSHEET_URL blank for the first run; the script creates a Sheet and logs its link.
 * 4. Click Preview, then Run. Schedule it daily.
 */

// ---- Settings -------------------------------------------------------------------------
var MONTHLY_BUDGET = 10000;         // This month's budget, in the account's currency.
var CAMPAIGN_NAME_CONTAINS = '';    // Only include campaigns whose name contains this. Blank = all.
var TOLERANCE = 0.10;               // Email when the projection is more than 10% over or under.
var SPREADSHEET_URL = '';           // Blank = create a new Sheet. Paste a Sheet URL here to reuse it.
var EMAIL = '';                     // Optional: one address, or several separated by commas.
// ----------------------------------------------------------------------------------------

var BRAND = { ink: '#06222e', pink: '#ff2e7e', soft: '#eaf6fa', quiet: '#3a5763', white: '#ffffff' };

function main() {
  var account = AdsApp.currentAccount();
  var tz = account.getTimeZone();
  var currency = account.getCurrencyCode();
  var now = new Date();
  var today = Utilities.formatDate(now, tz, 'yyyy-MM-dd');
  var y = Number(today.slice(0, 4)), m = Number(today.slice(5, 7)), d = Number(today.slice(8, 10));
  var daysInMonth = new Date(Date.UTC(y, m, 0)).getUTCDate();
  var monthStart = today.slice(0, 8) + '01';
  var elapsed = d - 1;                       // full days so far, up to yesterday
  var daysLeft = daysInMonth - elapsed;      // including today

  if (elapsed === 0) {
    Logger.log('It is the first day of the month, so there is no spend to pace yet.');
    return;
  }
  var yesterday = Utilities.formatDate(new Date(now.getTime() - 864e5), tz, 'yyyy-MM-dd');
  var daily = fetchDaily_(monthStart, yesterday);
  var dates = [];
  for (var i = 1; i <= elapsed; i++) dates.push(today.slice(0, 8) + (i < 10 ? '0' : '') + i);

  var spend = 0, cumulative = [];
  dates.forEach(function (date, idx) {
    spend += daily.byDate[date] || 0;
    cumulative.push([date, round_(daily.byDate[date] || 0), round_(spend), round_(MONTHLY_BUDGET * (idx + 1) / daysInMonth)]);
  });
  var last7 = dates.slice(-7);
  var runRate = last7.reduce(function (a, dt) { return a + (daily.byDate[dt] || 0); }, 0) / last7.length;
  var ideal = MONTHLY_BUDGET * elapsed / daysInMonth;
  var projected = spend + runRate * daysLeft;
  var needed = Math.max(0, (MONTHLY_BUDGET - spend) / daysLeft);
  var pace = ideal ? spend / ideal : 0;
  var gap = MONTHLY_BUDGET ? (projected - MONTHLY_BUDGET) / MONTHLY_BUDGET : 0;
  var status = Math.abs(gap) <= TOLERANCE ? 'On track' : gap > 0 ? 'Heading over budget' : 'Heading under budget';

  var summary = {
    month: Utilities.formatDate(now, tz, 'MMMM yyyy'), currency: currency, budget: MONTHLY_BUDGET, spend: spend,
    ideal: ideal, pace: pace, runRate: runRate, projected: projected, needed: needed, status: status, gap: gap,
    elapsed: elapsed, daysInMonth: daysInMonth, daysLeft: daysLeft
  };
  var ss = openSpreadsheet_(account.getName());
  writePacing_(ss, account.getName(), summary, cumulative, daily.byCampaign, last7);
  Logger.log(status + ': spent ' + round_(spend) + ' of ' + MONTHLY_BUDGET + ', projected ' + round_(projected) + '. Sheet: ' + ss.getUrl());

  if (EMAIL && status !== 'On track') {
    MailApp.sendEmail({
      to: EMAIL,
      subject: 'Budget pacing: ' + account.getName() + ' is ' + status.toLowerCase() + ' (' + summary.month + ')',
      htmlBody: emailHtml_(account.getName(), summary, ss.getUrl())
    });
  }
}

function fetchDaily_(from, to) {
  var query =
    'SELECT campaign.name, segments.date, metrics.cost_micros FROM campaign ' +
    "WHERE segments.date BETWEEN '" + from + "' AND '" + to + "' AND metrics.cost_micros > 0";
  var rows = AdsApp.search(query);
  var byDate = {}, byCampaign = {};
  var filter = CAMPAIGN_NAME_CONTAINS.toLowerCase();
  while (rows.hasNext()) {
    var r = rows.next();
    var name = String(r.campaign.name);
    if (filter && name.toLowerCase().indexOf(filter) < 0) continue;
    var cost = num_(r.metrics.costMicros) / 1e6;
    byDate[r.segments.date] = (byDate[r.segments.date] || 0) + cost;
    var c = byCampaign[name] || (byCampaign[name] = { total: 0, days: {} });
    c.total += cost;
    c.days[r.segments.date] = (c.days[r.segments.date] || 0) + cost;
  }
  return { byDate: byDate, byCampaign: byCampaign };
}

function writePacing_(ss, accountName, s, cumulative, byCampaign, last7) {
  var sh = ss.getSheetByName('Pacing') || ss.insertSheet('Pacing', 0);
  sh.getCharts().forEach(function (c) { sh.removeChart(c); });
  sh.clear();
  var blank = ss.getSheetByName('Sheet1');
  if (blank && ss.getSheets().length > 1 && blank.getLastRow() === 0) ss.deleteSheet(blank);

  sh.getRange('A1').setValue('Budget pacing · ' + s.month).setFontSize(20).setFontWeight('bold').setFontColor(BRAND.ink);
  sh.getRange('A2').setValue(accountName + '  ·  updated ' + cumulative[cumulative.length - 1][0] +
    (CAMPAIGN_NAME_CONTAINS ? '  ·  campaigns containing "' + CAMPAIGN_NAME_CONTAINS + '"' : '')).setFontColor(BRAND.quiet);
  sh.getRange('A3').setValue(s.status).setFontWeight('bold').setFontSize(13)
    .setFontColor(s.status === 'On track' ? '#1d6b3f' : '#c20a52');

  var labels = ['Budget', 'Spent so far', 'Should have spent', 'Pace', 'Last 7 days, per day', 'Projected month end', 'Needed per day to land on budget'];
  var values = [s.budget, round_(s.spend), round_(s.ideal), s.pace, round_(s.runRate), round_(s.projected), round_(s.needed)];
  sh.getRange(5, 1, 1, labels.length).setValues([labels]).setFontColor(BRAND.quiet).setFontSize(9).setWrap(true);
  sh.getRange(6, 1, 1, values.length).setValues([values]).setFontSize(15).setFontWeight('bold').setFontColor(BRAND.ink)
    .setNumberFormat('#,##0');
  sh.getRange(6, 4).setNumberFormat('0%');
  sh.getRange(7, 1).setValue('Amounts in ' + s.currency + '. Day ' + s.elapsed + ' of ' + s.daysInMonth + ', ' + s.daysLeft + ' days left including today.')
    .setFontColor(BRAND.quiet).setFontSize(9);

  // Daily table, feeding the chart.
  var top = 9;
  var head = [['Date', 'Spend', 'Cumulative spend', 'Ideal cumulative']];
  sh.getRange(top, 1, 1, 4).setValues(head).setBackground(BRAND.ink).setFontColor(BRAND.white).setFontWeight('bold');
  sh.getRange(top + 1, 1, cumulative.length, 4).setValues(cumulative);
  sh.getRange(top + 1, 2, cumulative.length, 3).setNumberFormat('#,##0.00');
  bands_(sh, top + 1, 4, cumulative.length);

  var chart = sh.newChart().asLineChart()
    .addRange(sh.getRange(top, 1, cumulative.length + 1, 1))
    .addRange(sh.getRange(top, 3, cumulative.length + 1, 2))
    .setNumHeaders(1)
    .setTitle('Cumulative spend against ideal')
    .setColors([BRAND.pink, '#7fa7b5'])
    .setOption('series', { 1: { lineDashStyle: [6, 4] } })
    .setOption('vAxis.format', '#,##0')
    .setOption('width', 620)
    .setOption('height', 320)
    .setPosition(top, 6, 0, 0)
    .build();
  sh.insertChart(chart);

  // Campaign table.
  var ctop = top + cumulative.length + 3;
  sh.getRange(ctop, 1).setValue('By campaign').setFontWeight('bold').setFontSize(13).setFontColor(BRAND.ink);
  var chead = ['Campaign', 'Spent so far', 'Share', 'Last 7 days, per day'];
  var crow = Object.keys(byCampaign).map(function (name) {
    var c = byCampaign[name];
    var l7 = last7.reduce(function (a, dt) { return a + (c.days[dt] || 0); }, 0) / last7.length;
    return [name, round_(c.total), s.spend ? c.total / s.spend : 0, round_(l7)];
  }).sort(function (a, b) { return b[1] - a[1]; });
  sh.getRange(ctop + 1, 1, 1, 4).setValues([chead]).setBackground(BRAND.ink).setFontColor(BRAND.white).setFontWeight('bold');
  if (crow.length) {
    sh.getRange(ctop + 2, 1, crow.length, 4).setValues(crow);
    sh.getRange(ctop + 2, 2, crow.length, 1).setNumberFormat('#,##0.00');
    sh.getRange(ctop + 2, 3, crow.length, 1).setNumberFormat('0%');
    sh.getRange(ctop + 2, 4, crow.length, 1).setNumberFormat('#,##0.00');
    bands_(sh, ctop + 2, 4, crow.length);
  }
  sh.getRange(ctop + 3 + crow.length, 1).setValue('Free script from Second Query · secondquery.com/google-ads-scripts')
    .setFontColor(BRAND.pink).setFontSize(9);
  sh.setColumnWidth(1, 260);
  for (var col = 2; col <= 4; col++) sh.setColumnWidth(col, 130);
  sh.setFrozenRows(0);
  sh.setHiddenGridlines(true);
}

function emailHtml_(accountName, s, url) {
  var money = function (v) { return s.currency + ' ' + Math.round(v).toLocaleString('en-GB'); };
  var line = function (k, v) { return '<tr><td style="padding:6px 12px 6px 0;color:#3a5763">' + k + '</td><td style="padding:6px 0;font-weight:bold">' + v + '</td></tr>'; };
  return '<div style="font:15px Arial,sans-serif;color:#06222e;max-width:620px">' +
    '<p style="font-size:18px;font-weight:bold;margin:0 0 4px">' + accountName + ': ' + s.status.toLowerCase() + '</p>' +
    '<p style="margin:0 0 12px;color:#3a5763">' + s.month + ', day ' + s.elapsed + ' of ' + s.daysInMonth + '</p>' +
    '<table style="border-collapse:collapse">' +
    line('Budget', money(s.budget)) + line('Spent so far', money(s.spend)) + line('Projected month end', money(s.projected) + ' (' + (s.gap > 0 ? '+' : '') + Math.round(s.gap * 100) + '%)') +
    line('Last 7 days, per day', money(s.runRate)) + line('Needed per day to land on budget', money(s.needed)) +
    '</table><p style="margin:14px 0 0"><a href="' + url + '" style="color:#ff2e7e">Open the pacing sheet</a></p>' +
    '<p style="margin:14px 0 0;color:#3a5763;font-size:13px">Free script from <a href="https://secondquery.com/google-ads-scripts/" style="color:#ff2e7e">Second Query</a>.</p></div>';
}

function openSpreadsheet_(accountName) {
  if (SPREADSHEET_URL) return SpreadsheetApp.openByUrl(SPREADSHEET_URL);
  var ss = SpreadsheetApp.create('Budget pacing: ' + accountName);
  Logger.log('Created a new Sheet. Paste this into SPREADSHEET_URL to reuse it: ' + ss.getUrl());
  return ss;
}

function bands_(sh, startRow, cols, rows) {
  var colours = [];
  for (var i = 0; i < rows; i++) {
    var line = [];
    for (var j = 0; j < cols; j++) line.push(i % 2 ? BRAND.soft : BRAND.white);
    colours.push(line);
  }
  sh.getRange(startRow, 1, rows, cols).setBackgrounds(colours);
}

function num_(v) { var n = Number(v); return isFinite(n) ? n : 0; }
function round_(v) { return Math.round(v * 100) / 100; }

People also ask

Are these Google Ads scripts safe to run?
Yes. All three only read reporting data. They don't change bids, budgets, keywords or anything else, and you can read every line before you run them. Click Preview first to see exactly what each one would do.
Do I need a Google Sheet first?
No. Leave the spreadsheet setting blank and the script creates a Sheet in your Google Drive on the first run and logs its link. Paste that link into the setting so later runs update the same Sheet.
Do they work in a manager (MCC) account?
These versions are written for a single account. Add them to each account you want to cover, or ask me about a manager-account version for your team.
Can I change them?
Yes. They're free to use and adapt. Please keep the header so others can find the originals.

Want a senior view on what the numbers say?

The scripts show you where to look. If you'd like a second opinion on what to do about it, that's what the options for PPC teams are for.