Google Search Console Clicks and Impressions by Country

By Rohan Babbar10 min read
Google Search Console Clicks and Impressions by Country

I wanted to know which search queries brought clicks from the markets I was targeting. A country total shows where the clicks came from. Grouping by query and country together lets me see which of those clicks came from people searching for something other than my name.

I added QueryCountry.gs to an existing Google Sheets tracker. It pulls a rolling 90-day window, flags brand and target-market rows, and adds a summary to the daily export. The snippets below follow the build with synthetic examples and generic settings.

1. Add the script to the reporting workbook

From the Google Sheet, open Extensions → Apps Script and add QueryCountry.gs. The add-on reads two settings from the existing CFG object in Code.gs. Set gscSiteUrl to the exact Search Console property you can access and brandTerms to your brand names and spelling variants. For a test configuration, the values could be sc-domain:example.com and ['sample studio', 'samplestudio'].

Enable the Search Console API on the Apps Script project's linked Cloud project. For an explicit oauthScopes list, keep the existing scopes and check that it covers Search Console read access (webmasters.readonly), HTTP requests (script.external_request), the bound spreadsheet, trigger management (script.scriptapp), the effective user's email (userinfo.email), and alert delivery (script.send_mail). Use the spreadsheet scope appropriate to your existing script.

The example target list uses lowercase ISO 3166-1 alpha-3 codes. The exclusion rule catches legacy brand-lookup noise and keeps those rows visible for diagnosis.

const QC = {
  tab: 'GSC_Query_Country',
  exportTab: 'Claude_Export',
  block: 'GSC_QUERY_COUNTRY_90D',
  days: 90,                 // window length
  lagDays: 3,               // GSC data is final after ~2-3 days
  // GSC uses ISO-3166 alpha-3, lowercase. Example target markets
  targetCountries: ['ind', 'usa', 'gbr', 'can', 'aus', 'deu', 'nld', 'irl', 'swe', 'dnk', 'are', 'sgp', 'sau'],
  // Queries matching these are company-lookup / bot-like noise: kept in the tab, excluded from the KPI
  excludePatterns: [/old-brand-name/i],
  pageSize: 25000,
  tz: 'Asia/Kolkata',
  maxDataAgeDays: 5,        // alert if newest GSC data is older than this
};

2. Request finalized query × country rows

The end date is three days back. The start date is 89 days before the end date because Search Console includes both endpoints. The script formats dates in the report's configured timezone. The API interprets the submitted date labels in Pacific time, so use Pacific time for the API date calculation if you need strict alignment with the Search Console reporting day.

With dimensions: ['query', 'country'], keys[0] is the query and keys[1] is the country. Each call asks for up to 25,000 rows, and the offset advances by 25,000 until a short or empty page arrives. dataState: 'final' requests finalized data. Pagination retrieves the rows Search Console makes available for this request. Query-level results can omit anonymized or lower-volume data. Search Analytics API reference · Google’s data limits guide

function qc_fmt_(d) { return Utilities.formatDate(d, QC.tz, 'yyyy-MM-dd'); }

function qc_gsc_(body) {
  const url = 'https://searchconsole.googleapis.com/webmasters/v3/sites/' +
    encodeURIComponent(CFG.gscSiteUrl) + '/searchAnalytics/query';
  const res = UrlFetchApp.fetch(url, {
    method: 'post',
    contentType: 'application/json',
    headers: { Authorization: 'Bearer ' + ScriptApp.getOAuthToken() },
    payload: JSON.stringify(body),
    muteHttpExceptions: true,
  });
  if (res.getResponseCode() !== 200) throw new Error('GSC ' + res.getResponseCode() + ': ' + res.getContentText());
  return JSON.parse(res.getContentText()).rows || [];
}

3. Flag the rows and write them to Sheets

The refresh uses a case-insensitive substring match against the configured brand terms. Market status is Excluded for an exclusion match, Yes for a target country, and No otherwise. The script displays country codes in uppercase and sorts the table by impressions.

The KPI sums clicks where Brand/Non-brand = Non-brand and In Target Market = Yes. The same filter gives the companion impressions total. The share in the top row is the proportion of returned impressions from outside the target markets or from excluded rows.

This synthetic fixture shows the filter. Only the first row contributes to the KPI.

Synthetic query Country Clicks Impressions Brand flag Market flag
example warehouse demo USA 3 40 Non-brand Yes
sample studio login GBR 2 20 Brand Yes
old-brand-name support USA 1 12 Non-brand Excluded
example training quote NZL 1 10 Non-brand No

The refresh clears the previous contents, writes a summary and headers, then uses one setValues() call for the full body. It records the run timestamp only after the write completes.

function qc_run() {
  const end = new Date(Date.now() - QC.lagDays * 864e5);
  const start = new Date(end.getTime() - (QC.days - 1) * 864e5);
  const range = qc_fmt_(start) + '..' + qc_fmt_(end);

  const rows = [];
  for (let startRow = 0; ; startRow += QC.pageSize) {
    const page = qc_gsc_({
      startDate: qc_fmt_(start),
      endDate: qc_fmt_(end),
      dimensions: ['query', 'country'],
      rowLimit: QC.pageSize,
      startRow: startRow,
      dataState: 'final',
    });
    rows.push.apply(rows, page);
    if (page.length < QC.pageSize) break;
  }

  const brand = (typeof CFG !== 'undefined' && CFG.brandTerms) ? CFG.brandTerms : [];
  const out = rows.map(r => {
    const q = r.keys[0], c = r.keys[1];
    const isBrand = brand.some(t => q.toLowerCase().indexOf(t.toLowerCase()) !== -1);
    return [q, c.toUpperCase(), r.clicks, r.impressions, r.ctr, r.position,
            isBrand ? 'Brand' : 'Non-brand',
            QC.excludePatterns.some(re => re.test(q)) ? 'Excluded'
              : (QC.targetCountries.indexOf(c) !== -1 ? 'Yes' : 'No')];
  }).sort((a, b) => b[3] - a[3]);

  // KPI: non-brand, in target market
  const kpiRows = out.filter(r => r[6] === 'Non-brand' && r[7] === 'Yes');
  const kpiClicks = kpiRows.reduce((s, r) => s + r[2], 0);
  const kpiImpr = kpiRows.reduce((s, r) => s + r[3], 0);
  const totImpr = out.reduce((s, r) => s + r[3], 0);
  const outImpr = out.filter(r => r[7] !== 'Yes').reduce((s, r) => s + r[3], 0);

  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sh = ss.getSheetByName(QC.tab) || ss.insertSheet(QC.tab);
  sh.clearContents();
  sh.getRange(1, 1, 1, 8).setValues([[
    'Range', range + ' (rows: ' + out.length + ')',
    'Target-market non-brand clicks', kpiClicks,
    'Target-market non-brand impressions', kpiImpr,
    'Out-of-market + excluded impression share', totImpr ? outImpr / totImpr : 0,
  ]]);
  sh.getRange(1, 8).setNumberFormat('0.0%');
  const header = ['Query', 'Country', 'Clicks', 'Impressions', 'CTR', 'Position', 'Brand/Non-brand', 'In Target Market'];
  sh.getRange(2, 1, 1, header.length).setValues([header]).setFontWeight('bold');
  if (out.length) sh.getRange(3, 1, out.length, header.length).setValues(out); // one batch write
  sh.setFrozenRows(2);
  PropertiesService.getScriptProperties().setProperty('QC_LAST_RUN', new Date().toISOString());
  Logger.log('GSC_Query_Country rows: ' + out.length + '; KPI clicks ' + kpiClicks + ', impressions ' + kpiImpr);
}

4. Append the country block after the daily export

My first scheduling mistake was letting the export rebuild run after the country append. The rebuild cleared the export, so the query × country block disappeared. I kept the main export at 07:00 and scheduled the country append for around 07:30.

I also made the append safe to rerun. It keeps the export header, removes rows carrying the previous country block marker and its META row, then appends one replacement block. The timestamp can change on a rerun. The block appears once. The append expects the existing 16-column export layout and skips writing if either tab is missing or the source has no data rows.

function qc_afterExport() {
  qc_appendToExport();
  qc_healthCheck();
}

function qc_appendToExport() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const src = ss.getSheetByName(QC.tab);
  const ex = ss.getSheetByName(QC.exportTab);
  if (!src || !ex || src.getLastRow() < 3) return;

  // Remove any earlier copy of this block (safe to run twice)
  const exData = ex.getDataRange().getValues();
  const keep = exData.filter((r, i) => i === 0 || !(r[0] === QC.block || (r[0] === 'META' && r[14] === QC.block)));
  if (keep.length !== exData.length) {
    ex.clearContents();
    ex.getRange(1, 1, keep.length, keep[0].length).setValues(keep);
  }

  const head = src.getRange(1, 1, 1, 8).getValues()[0];
  const range = String(head[1]).split(' ')[0];
  const data = src.getRange(3, 1, src.getLastRow() - 2, 8).getValues();
  const stamp = Utilities.formatDate(new Date(), QC.tz, 'yyyy-MM-dd HH:mm');

  // 16 columns: block, period, page, query, link_url, channel, clicks, impressions,
  // ctr, position, sessions, engaged_sessions, key_events, event_count, status, note
  const meta = ['META', stamp, '', '', '', '', '', '', '', '', '', '', '', '', QC.block,
    'range ' + range + '; rows ' + data.length + '; channel = country (ISO alpha-3); status = TARGET/OUT/EXCLUDED (company-lookup noise); note = Brand/Non-brand; ' +
    'target-market non-brand clicks ' + head[3] + ', impressions ' + head[5] +
    '; out-of-market + excluded impression share ' + (Number(head[7]) * 100).toFixed(1) + '%'];
  const rows = data.map(r => [QC.block, range, '', r[0], '', r[1], r[2], r[3], r[4], r[5],
    '', '', '', '', r[7] === 'Yes' ? 'TARGET' : (r[7] === 'Excluded' ? 'EXCLUDED' : 'OUT'), r[6]]);

  const all = [meta].concat(rows);
  ex.getRange(ex.getLastRow() + 1, 1, all.length, 16).setValues(all);
}

5. Install the triggers and check that alerts work

Run qc_run manually to grant authorization and check the source tab. After the main export exists, run qc_afterExport once and confirm there is one country block. Run it a second time to confirm the old block is replaced. Then run qc_setupTriggers once. It replaces existing triggers for the two add-on handlers. Keep the main export's existing trigger and align the project timezone with the report timezone. The refresh is scheduled for around 06:30 and the append plus health check for around 07:30. Apps Script’s nearMinute() can vary by 15 minutes, so verify the export normally finishes before the append runs. Apps Script clock trigger reference

function qc_setupTriggers() {
  ScriptApp.getProjectTriggers()
    .filter(t => ['qc_run', 'qc_afterExport'].indexOf(t.getHandlerFunction()) !== -1)
    .forEach(t => ScriptApp.deleteTrigger(t));
  ScriptApp.newTrigger('qc_run').timeBased().everyDays(1).atHour(6).nearMinute(30).create();
  ScriptApp.newTrigger('qc_afterExport').timeBased().everyDays(1).atHour(7).nearMinute(30).create();
  Logger.log('Triggers set: qc_run ~06:30, qc_afterExport ~07:30');
}

The health check looks for a missing export or refresh marker, an earlier refresh date, data more than five days old when the metadata contains a latest-data date, error text in export metadata, and a missing same-day query × country refresh. It emails the trigger owner when it finds problems. This is a check inside the scheduled job, so a trigger that never starts still needs monitoring through Apps Script Executions.

Two authorization failures mattered in practice.

  • OAuth in Testing. For this external app, the testing refresh token expired after seven days and unattended triggers stalled. I published the privacy page, set the consent screen to In production, reauthorized, and ran the refresh again. Google OAuth token expiration rules
  • Alert email permission. The job could detect a problem, but email delivery failed until I added https://www.googleapis.com/auth/script.send_mail to the existing oauthScopes list in appsscript.json and reauthorized the trigger owner. Apps Script MailApp reference
function qc_healthCheck() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const today = qc_fmt_(new Date());
  const problems = [];

  const ex = ss.getSheetByName(QC.exportTab);
  if (!ex) {
    problems.push('Claude_Export tab is missing.');
  } else {
    const meta = ex.getDataRange().getValues().filter(r => r[0] === 'META');
    const refresh = meta.find(r => r[14] === 'REFRESH');
    if (!refresh) problems.push('Claude_Export has no REFRESH row.');
    else {
      if (String(refresh[1]).slice(0, 10) !== today) problems.push('Claude export last ran ' + refresh[1] + ', not today.');
      const m = String(refresh[15]).match(/latest data (\d{4}-\d{2}-\d{2})/);
      if (m) {
        const ageDays = (new Date(today) - new Date(m[1])) / 864e5;
        if (ageDays > QC.maxDataAgeDays) problems.push('Newest Search Console data is ' + m[1] + ' (' + ageDays + ' days old).');
      }
    }
    meta.filter(r => /error|exception|failed|denied|disabled/i.test(String(r[15])))
        .forEach(r => problems.push('Error in ' + r[14] + ': ' + String(r[15]).slice(0, 200)));
  }

  const last = PropertiesService.getScriptProperties().getProperty('QC_LAST_RUN');
  if (!last || qc_fmt_(new Date(last)) !== today) problems.push('Query x country refresh (qc_run) did not run today.');

  if (problems.length) {
    MailApp.sendEmail(Session.getEffectiveUser().getEmail(),
      'Search Console report: refresh problem (' + today + ')',
      problems.join('\n') + '\n\nFix: open the sheet > Extensions > Apps Script > run refreshAll, then cx_runClaudeExport, qc_run and qc_afterExport.\n' +
      'If you see "Access blocked" or an expired login, check the OAuth consent screen is In production.');
  }
  Logger.log(problems.length ? problems.join(' | ') : 'Health check OK');
}

How I’d use this across four industries

Industry What I’d look for
E-commerce Non-brand category queries in countries the store ships to, then compare with product landing pages and purchases.
B2B Solution and integration queries in sales territories, then compare with qualified enquiries.
Education Course and programme queries in recruitment markets, then compare with application starts.
Services Service and problem queries in locations the team can support, then compare with quote requests.

Clicks show search visits. To investigate what visitors do next, see how I connected GA4 to Claude. For a separate lead intake workflow, see how I routed Meta Lead Ads to Google Sheets.

FAQ

Can I get Google Search Console clicks and impressions by country?

Yes. Use the country dimension in Search Analytics. Add query as a second dimension if you need to see the query behind each country row and flag brand terms.

Why does the report end three days back?

The build uses a three-day buffer and requests final data. The date window is inclusive, so subtract 89 more days from the end date to request 90 days.

Why might the query-by-country total differ from the country total?

Search Console can omit anonymized queries and limit the query rows returned. Use a country-only request when you need a country total and the query-by-country report when you need the query breakdown.

Can I rerun the export append without duplicating rows?

Yes. The append removes the prior block rows and their metadata row before writing the current block. Run it after the main export has finished.

If you need help building a reporting workflow around the markets you serve, see my digital marketing consulting work or contact me on LinkedIn or Gmail.

google search consoleapps scriptseo reporting
ShareLinkedInX
Rohan Babbar
Rohan Babbar

Digital marketing, SEO and paid media. Connect on LinkedIn