GAQL (Google Ads Query Language) is the SQL-like language for extracting data from Google Ads accounts via the API. If you manage Google Ads campaigns at scale — multiple accounts, automated reporting, or programmatic bid adjustments — GAQL replaces the web interface's point-and-click reports with precise, scriptable queries. This guide covers the essential queries, Python client setup, pagination, error handling, and automation patterns that every developer working with Google Ads needs. For a live exploration of GAQL queries, try our GAQL Explorer demo.
Need help with AI tools and integrations? I provide AI tools and integrations for businesses ready to grow. Learn about my AI tools and integrations service or get in touch for a free consultation.
- Understanding GAQL Syntax
- Essential GAQL Queries
- Error Handling
- Advanced Query Patterns
Understanding GAQL Syntax
GAQL looks like SQL but operates on Google Ads resources rather than database tables. Each query selects fields from a resource (like a table), optionally filters with WHERE clauses, and optionally orders results. The key differences from SQL: there is no JOIN (relationships are built into resource schemas), no GROUP BY (aggregation is implicit based on the segments you include), and date ranges are specified in WHERE clauses rather than on the query itself.
-- Basic GAQL structure
SELECT
campaign.name,
campaign.status,
metrics.impressions,
metrics.clicks,
metrics.cost_micros,
metrics.conversions
FROM campaign
WHERE campaign.status = 'ENABLED'
AND segments.date DURING LAST_30_DAYS
ORDER BY metrics.clicks DESC
LIMIT 50
Costs in the Google Ads API are returned in micros (millionths of the account currency). To get dollars, divide by 1,000,000. This is a common source of bugs — reporting $45 million instead of $45 — so always apply the conversion in your data processing pipeline, never rely on doing it mentally or in a spreadsheet formula.
Setting Up the Python Client
The google-ads Python library handles authentication, request signing, and response parsing. Set it up with OAuth2 credentials from your Google Cloud project.
# Install the client
pip install google-ads
# google-ads.yaml (credentials file)
developer_token: YOUR_DEVELOPER_TOKEN
client_id: YOUR_CLIENT_ID
client_secret: YOUR_CLIENT_SECRET
refresh_token: YOUR_REFRESH_TOKEN
login_customer_id: "1234567890" # Manager account ID, no dashes
# Python client setup
from google.ads.googleads.client import GoogleAdsClient
client = GoogleAdsClient.load_from_storage("google-ads.yaml")
ga_service = client.get_service("GoogleAdsService")
def run_query(customer_id, query):
'''Execute a GAQL query and return rows as dicts.'''
response = ga_service.search_stream(
customer_id=customer_id,
query=query,
)
results = []
for batch in response:
for row in batch.results:
results.append(row)
return results
Use search_stream instead of search for large result sets. The streaming version processes rows as they arrive rather than loading the entire response into memory, which matters when pulling campaign or keyword data for accounts with millions of rows. The non-streaming search method paginates automatically but loads each page fully, which can cause memory issues for very large queries.
Each query selects fields from a resource (like a table), optionally filters with WHERE clauses, and optionally orders results.
Essential GAQL Queries
These queries cover the reports most Google Ads managers need daily. Each is production-tested and includes the fields that actually drive optimization decisions.
Campaign Performance Report
SELECT
campaign.id,
campaign.name,
campaign.status,
campaign.advertising_channel_type,
campaign_budget.amount_micros,
metrics.impressions,
metrics.clicks,
metrics.cost_micros,
metrics.conversions,
metrics.conversions_value,
metrics.cost_per_conversion,
metrics.search_impression_share
FROM campaign
WHERE segments.date DURING LAST_30_DAYS
AND campaign.status != 'REMOVED'
ORDER BY metrics.cost_micros DESC
Keyword Analysis Report
SELECT
ad_group.name,
ad_group_criterion.keyword.text,
ad_group_criterion.keyword.match_type,
ad_group_criterion.quality_info.quality_score,
metrics.impressions,
metrics.clicks,
metrics.cost_micros,
metrics.conversions,
metrics.average_cpc
FROM keyword_view
WHERE segments.date DURING LAST_30_DAYS
AND ad_group_criterion.status = 'ENABLED'
AND metrics.impressions > 100
ORDER BY metrics.cost_micros DESC
LIMIT 200
Search Terms Report (Finding New Keywords and Negatives)
SELECT
search_term_view.search_term,
search_term_view.status,
campaign.name,
ad_group.name,
metrics.impressions,
metrics.clicks,
metrics.cost_micros,
metrics.conversions
FROM search_term_view
WHERE segments.date DURING LAST_30_DAYS
AND metrics.impressions > 10
ORDER BY metrics.cost_micros DESC
LIMIT 500
The search terms report is where optimization gold lives. Sort by cost descending to find expensive queries that do not convert — these become negative keywords. Sort by conversions descending to find converting queries that you have not targeted explicitly — these become new keyword additions. Run this weekly for active accounts.
Geographic Performance Report
SELECT
geographic_view.country_criterion_id,
geographic_view.location_type,
campaign.name,
metrics.impressions,
metrics.clicks,
metrics.cost_micros,
metrics.conversions,
metrics.cost_per_conversion
FROM geographic_view
WHERE segments.date DURING LAST_30_DAYS
AND metrics.impressions > 50
ORDER BY metrics.conversions DESC
Geographic data reveals where your budget is producing results and where it is being wasted. A plumber in Phoenix spending money on clicks from Tucson (150 miles away) needs geographic bid adjustments. For more on geographic optimization, see our guide to Google Ads costs for service businesses.
Ad Schedule Performance
SELECT
campaign.name,
segments.hour,
segments.day_of_week,
metrics.impressions,
metrics.clicks,
metrics.cost_micros,
metrics.conversions
FROM campaign
WHERE segments.date DURING LAST_30_DAYS
AND campaign.status = 'ENABLED'
ORDER BY segments.day_of_week, segments.hour
When working on Essential GAQL Queries, pick one measurable goal first, track it weekly, and only scale what the data shows is working.
Pagination and Large Result Sets
When using search (non-streaming), the API returns results in pages of up to 10,000 rows. The response includes a next_page_token that you pass in subsequent requests. The streaming API (search_stream) handles this automatically, making it the preferred choice for most use cases.
def run_query_paginated(customer_id, query, page_size=10000):
'''Non-streaming paginated query for smaller result sets.'''
all_results = []
request = client.get_type("SearchGoogleAdsRequest")
request.customer_id = customer_id
request.query = query
request.page_size = page_size
while True:
response = ga_service.search(request=request)
for row in response.results:
all_results.append(row)
if not response.next_page_token:
break
request.page_token = response.next_page_token
return all_results
For very large exports (millions of rows), process rows in the streaming callback rather than accumulating them in a list. Write directly to a CSV file or database table to keep memory usage constant regardless of result set size.
Want expert help with this? Let's make it happen.
Get a Free ConsultationError Handling
Google Ads API errors fall into several categories, each requiring a different response strategy. Transient errors (rate limiting, server errors) should be retried with exponential backoff. Permanent errors (invalid queries, authentication failures) should be logged and reported immediately.
from google.api_core.exceptions import GoogleAPICallError, ResourceExhausted
import time
def run_query_safe(customer_id, query, max_retries=3):
'''Execute a GAQL query with retry logic for transient errors.'''
for attempt in range(max_retries):
try:
return run_query(customer_id, query)
except ResourceExhausted:
# Rate limited — back off exponentially
wait = 2 ** attempt * 10 # 10s, 20s, 40s
print(f"Rate limited, waiting {wait}s...")
time.sleep(wait)
except GoogleAPICallError as e:
if "INTERNAL" in str(e):
# Server-side issue, retry
time.sleep(5)
continue
# Permanent error — do not retry
raise
raise Exception(f"Failed after {max_retries} retries")
The most common errors you will encounter: QUERY_ERROR means your GAQL syntax is wrong or you are selecting incompatible fields (not all fields can be selected together). AUTHORIZATION_ERROR means your credentials have expired or the customer account has been delinked from your manager account. RESOURCE_EXHAUSTED means you have hit the daily API quota — the default is 15,000 requests per day per developer token.
Automation: Scheduled Reports
Automate your reporting pipeline with Django management commands and Celery Beat for scheduling. This pattern generates daily reports for all accounts under a manager account and stores them in your database for dashboarding and alerting.
# management/commands/pull_ads_data.py
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = "Pull Google Ads campaign data for all active accounts"
def handle(self, *args, **options):
accounts = AdsAccount.objects.filter(active=True)
for account in accounts:
try:
rows = run_query_safe(
account.customer_id,
CAMPAIGN_PERFORMANCE_QUERY,
)
self.save_campaign_data(account, rows)
self.stdout.write(f" OK: {account.name} ({len(rows)} campaigns)")
except Exception as e:
self.stderr.write(f" FAIL: {account.name}: {e}")
def save_campaign_data(self, account, rows):
for row in rows:
CampaignMetric.objects.update_or_create(
account=account,
campaign_id=row.campaign.id,
date=row.segments.date,
defaults={
"name": row.campaign.name,
"cost": row.metrics.cost_micros / 1_000_000,
"clicks": row.metrics.clicks,
"conversions": row.metrics.conversions,
"impressions": row.metrics.impressions,
},
)
Schedule this command to run daily at 6 AM via Celery Beat or cron. Google Ads data is typically finalized 3-6 hours after the end of a day, so a 6 AM pull captures the previous day's complete data. For more advanced reporting and account auditing, combine multiple queries to build a comprehensive picture of account health. Our Ads Auditor demo shows what automated account analysis looks like in practice, and our AI tools service can build a custom reporting pipeline tailored to your specific KPIs.
Advanced Query Patterns
Beyond the basics, GAQL supports patterns that unlock deeper analysis. Use segments.conversion_action to break down conversions by type — distinguishing phone calls from form fills from purchases. Use segments.ad_network_type to separate Search from Display from Partner network performance. Combine multiple segments to create multidimensional pivot tables in a single query.
One powerful pattern is change history queries, which show what changes were made to an account and when. This is invaluable for diagnosing performance drops — you can correlate a sudden CPA increase with a bid strategy change made two days earlier. The change_event resource provides this data programmatically, letting you build automated alerts for high-risk changes like budget modifications, campaign pauses, or bid strategy switches.
For teams managing multiple accounts, build a comparison framework that runs the same set of queries across all accounts and flags outliers. An account with a CPL 3x the portfolio average, or one with a sudden 50% drop in impression share, needs immediate attention. This kind of automated monitoring is what separates reactive account management from proactive optimization, and it is the foundation of the smart bidding strategies we implement for our clients.
Related reading: Conversion Rate Optimization Services: What They Include and What They Cost — what CRO work actually involves and how to judge whether the price is fair.



Frequently asked questions
How much should I budget for Google Ads as a small business?
Most local service businesses spend $1,000-5,000 per month on Google Ads. The right budget depends on your market, competition, and cost per lead. Start with $1,500-2,000/month to gather data, then scale based on cost per lead and conversion rates.
How long does it take to see results from Google Ads?
Initial data takes 2-4 weeks. Meaningful optimization requires 60-90 days of data. Smart bidding strategies need at least 30 conversions per month to perform well. Expect 3 months before the account reaches steady-state performance.
Should I manage Google Ads myself or hire someone?
If your monthly spend is under $2,000, self-management with Google's tools is viable. Above that, professional management typically pays for itself through better targeting, bid optimization, and negative keyword management that reduces wasted spend by 20-40%.
Desarrollador full-stack especializado en Django, automatización con IA y gestión de Google Ads. Construyo plataformas SaaS de producción y aplicaciones web personalizadas para empresas en todo EE.UU.