SQL for Marketers: The 10 Queries You'll Actually Use on Your Warehouse
SQL lets marketers answer their own questions from the warehouse. Here are the 10 queries that cover most marketing work, how to check them and how to keep BigQuery costs low.
SQL for marketers means writing small queries against your data warehouse to answer your own questions. You don't need to become an engineer. Ten patterns cover most of the work: counting leads, cleaning sources, building funnels, finding first touch and reading GA4 events. Learn those, learn the grain of your tables, and check every result.
In my experience, the best way to learn it is one real question at a time. This guide is built that way: each query answers a question a marketer actually asks.
You'll get the mental model, the ten queries with code, a cost check for BigQuery, a worked example of one dashboard query done two ways, the checks I run before I trust a number and the mistakes that cause most wrong answers.
Key takeaways
- Ten patterns cover most marketing questions. Count, clean, bucket, funnel, join, rank and unnest.
- Grain is the whole game. Know what one row means in every table before you join it.
- Joins double count by default. Roll up the many side first, then join.
- On BigQuery you pay for bytes read. Pick columns, filter dates, and never trust LIMIT to save money.
- Check before you share. Match one number to a source you trust before it goes in a deck.
Why should marketers learn SQL?
SQL is the language you use to ask questions of a database. Your CRM, ad platforms and analytics tools each answer some questions well. But the questions that matter most cut across them. Which channel brings leads that close? How long do demo requests wait? What share of last quarter's signups bought?
Those answers live in a data warehouse, where data from every tool lands in one place. If you can write SQL, you can answer them yourself, today. If you can't, you file a ticket and wait.
There's a second reason. When you can read the query behind a number, you can tell if the number is right. Most bad marketing reports aren't lies. They're joins that counted the same deal three times. If you're still deciding whether you need a warehouse at all, start with my guide to data warehouses for startups.
What do you need before you write a query?
Three things: access, a map of the tables and the grain of each one.
Access. Ask for read-only access. You only need to read. Read-only access means you can't change or delete anything, which makes it safe to learn on real data.
A map of the tables. Most marketing warehouses have some version of these:
| Table | One row is | Key columns |
|---|---|---|
| contacts | One person | contact_id, email, created_at, lead_source, utm_source, utm_medium, company_id |
| companies | One company | company_id, domain, employees, industry |
| deals | One deal | deal_id, company_id, created_at, closed_at, stage, amount, is_won |
| touches | One touch by one person | contact_id, touched_at, channel, campaign |
| GA4 events | One event (more or less) | event_date, event_timestamp, event_name, event_params, user_pseudo_id |
The grain. Grain means what one row stands for. One row per contact. One row per deal. One row per event. Every wrong number I've chased came back to grain. If you join a table with one row per company to a table with one row per deal, you get one row per deal, and the company's numbers repeat.
My post on the GTM data model goes deep on objects, keys and grain. Read it next if joins confuse you.
How does a SQL query run?
You write a query in one order, and the database runs it in another. Knowing the real order explains most errors.
| You write | The database runs | What it does |
|---|---|---|
| SELECT | 5th | Picks the columns and does the math |
| FROM, JOIN | 1st | Picks the tables and links them |
| WHERE | 2nd | Drops rows before grouping |
| GROUP BY | 3rd | Squashes rows into groups |
| HAVING | 4th | Drops groups after grouping |
| ORDER BY | 6th | Sorts the result |
| LIMIT | 7th | Cuts the result to N rows |
Two things follow. First, WHERE can't filter on a total, because totals don't exist yet. Use HAVING for that. Second, LIMIT runs last. It shortens what you see, not what the database reads. That matters for cost, as you'll see below.
Which 10 queries do marketers use most?
The examples use PostgreSQL syntax, with notes where BigQuery differs. The table names match the map above. Swap in your own.
1. How do you look at the raw rows first?
Always look before you count. Ten rows tell you more about the data than any summary.
SELECT contact_id, email, created_at, lead_source, utm_source, utm_medium
FROM contacts
WHERE created_at >= '2026-05-01'
ORDER BY created_at DESC
LIMIT 20;
Name your columns instead of using SELECT star. It's faster to read, and on some warehouses it's much cheaper.
2. How many leads came in each month, by source?
This is the query behind half of all marketing dashboards. The trick is date_trunc, which rounds a timestamp down to the start of a month, week or day. The PostgreSQL date functions docs describe it as like trunc for numbers: it zeroes out everything smaller than the unit you pick.
SELECT
date_trunc('month', created_at) AS month,
lead_source,
COUNT(*) AS leads
FROM contacts
WHERE created_at >= '2026-01-01'
GROUP BY 1, 2
ORDER BY 1, 3 DESC;
In BigQuery, the same idea is DATE_TRUNC(DATE(created_at), MONTH). The logic doesn't change. Only the spelling does.
3. How do you find duplicate contacts?
Compare the row count with the count of unique emails. If they differ, you have duplicates. This is the first step of any deduplication job.
SELECT
COUNT(*) AS rows,
COUNT(DISTINCT lower(trim(email))) AS unique_emails
FROM contacts;
-- Then list the worst offenders
SELECT lower(trim(email)) AS email, COUNT(*) AS copies
FROM contacts
GROUP BY 1
HAVING COUNT(*) > 1
ORDER BY copies DESC
LIMIT 50;
Note the lower(trim(...)). "Dana@Acme.com " and "dana@acme.com" are the same person, but not to the database.
4. How do you group messy sources into channels?
Raw UTM parameters are a mess. "linkedin", "LinkedIn" and "li" all mean the same thing. A CASE statement maps them into a short list of channels.
SELECT
CASE
WHEN lower(utm_medium) IN ('cpc', 'ppc', 'paid') THEN 'Paid search'
WHEN lower(utm_source) IN ('linkedin', 'li') AND lower(utm_medium) = 'paid_social' THEN 'Paid social'
WHEN lower(utm_medium) = 'email' THEN 'Email'
WHEN utm_source IS NULL AND lead_source = 'organic' THEN 'Organic'
ELSE 'Other'
END AS channel,
COUNT(*) AS leads
FROM contacts
GROUP BY 1
ORDER BY 2 DESC;
Watch the size of "Other". If it's big, your mapping has gaps. Once the mapping is stable, move it into a shared model so every report uses the same one. That's what tools like dbt are for.
5. How do you build a funnel in one query?
Use conditional counts. Each column counts the contacts that reached a stage. Then divide.
SELECT
date_trunc('month', c.created_at) AS cohort_month,
COUNT(*) AS leads,
SUM(CASE WHEN c.became_mql_at IS NOT NULL THEN 1 ELSE 0 END) AS mqls,
SUM(CASE WHEN c.became_sql_at IS NOT NULL THEN 1 ELSE 0 END) AS sqls,
ROUND(100.0 * SUM(CASE WHEN c.became_sql_at IS NOT NULL THEN 1 ELSE 0 END) / COUNT(*), 1) AS lead_to_sql_pct
FROM contacts c
GROUP BY 1
ORDER BY 1;
Two details. Multiply by 100.0, not 100, or some databases do whole-number division and give you zero. And group by when the lead was created, not when the stage was reached, so each row is one cohort. To model what a lift at each stage is worth, drop your rates into the funnel conversion calculator.
6. How do you join leads to deals without double counting?
This is the mistake behind most wrong revenue numbers. One company has many contacts. If you join contacts to deals on company_id and sum the amount, each deal counts once per contact.
The fix: roll up the many side first, then join. A CTE, which is a named sub-query that starts with WITH, keeps it readable.
WITH company_revenue AS (
SELECT company_id, SUM(amount) AS won_amount, COUNT(*) AS won_deals
FROM deals
WHERE is_won = true
GROUP BY company_id
),
company_source AS (
SELECT company_id, MIN(lead_source) AS lead_source -- pick one rule and write it down
FROM contacts
GROUP BY company_id
)
SELECT s.lead_source, SUM(r.won_amount) AS won_amount, SUM(r.won_deals) AS won_deals
FROM company_revenue r
JOIN company_source s USING (company_id)
GROUP BY 1
ORDER BY 2 DESC;
Now each company appears once on each side. The MIN is a crude rule for picking one source per company. A better rule is the next query.
7. How do you find each contact's first touch?
Window functions do this. The PostgreSQL tutorial on window functions puts it simply: a window function does a calculation across rows related to the current row, but the rows keep their own identity. Unlike GROUP BY, nothing gets squashed.
ROW_NUMBER() numbers each contact's touches in time order. Keep row 1, and you have first touch attribution.
WITH ranked AS (
SELECT
contact_id, channel, campaign, touched_at,
ROW_NUMBER() OVER (PARTITION BY contact_id ORDER BY touched_at) AS touch_rank
FROM touches
)
SELECT channel, COUNT(*) AS first_touches
FROM ranked
WHERE touch_rank = 1
GROUP BY 1
ORDER BY 2 DESC;
Change ORDER BY touched_at to ORDER BY touched_at DESC and you get last touch. That one-word change is a good way to see how much the model choice moves your numbers. My guide to marketing attribution models covers which to trust.
8. How long do leads wait for a first reply?
Subtract two timestamps, then look at the median and the slow tail. The average hides the slow tail.
SELECT
lead_source,
COUNT(*) AS leads,
percentile_cont(0.5) WITHIN GROUP (ORDER BY first_touch_at - created_at) AS median_wait,
percentile_cont(0.9) WITHIN GROUP (ORDER BY first_touch_at - created_at) AS p90_wait
FROM contacts
WHERE hand_raise = 'demo_request'
AND created_at >= now() - interval '90 days'
GROUP BY 1;
In BigQuery, use TIMESTAMP_DIFF for the gap and APPROX_QUANTILES for the percentiles. Why the 90th percentile matters is in my speed to lead playbook.
9. How do cohorts convert over time?
Cohort analysis groups people by when they started, then tracks what they did next. This query asks: of each month's signups, what share became customers within 90 days?
SELECT
date_trunc('month', c.created_at) AS signup_month,
COUNT(*) AS signups,
SUM(CASE WHEN c.became_customer_at <= c.created_at + interval '90 days' THEN 1 ELSE 0 END) AS customers_90d,
ROUND(100.0 * SUM(CASE WHEN c.became_customer_at <= c.created_at + interval '90 days' THEN 1 ELSE 0 END) / COUNT(*), 1) AS pct_90d
FROM contacts c
WHERE c.created_at < now() - interval '90 days' -- only cohorts old enough to judge
GROUP BY 1
ORDER BY 1;
The WHERE line matters. Last month's cohort hasn't had 90 days yet, so it will always look worse. Leave it out until it has.
10. How do you read GA4 events in BigQuery?
GA4 can export raw events to BigQuery. Google's GA4 export schema explains the layout. Each day lands in a table named events_YYYYMMDD. The event_timestamp is in microseconds, in UTC. And event_params is a repeated record of keys and values, so one event can span several rows.
That repeated record is why you need UNNEST. It opens the list of parameters so you can pick the one you want.
-- BigQuery
SELECT
event_date,
(SELECT value.string_value FROM UNNEST(event_params) WHERE key = 'page_location') AS page,
COUNT(*) AS form_submits
FROM `my_project.analytics_123456.events_*`
WHERE _TABLE_SUFFIX BETWEEN '20260501' AND '20260531'
AND event_name = 'generate_lead' -- use your own form event name
GROUP BY 1, 2
ORDER BY 3 DESC;
The _TABLE_SUFFIX filter limits which daily tables get read. That's the single biggest cost saver on GA4 data, which brings us to money.
What does a SQL query cost on BigQuery?
Most warehouses charge in one of two ways: for compute time, or for data read. BigQuery's default is the second. Its pricing page lists on-demand queries at $6.25 per TiB processed, with the first 1 TiB each month free.
BigQuery stores data by column. So a query pays for the columns it reads, across the rows it scans. Three rules follow from Google's own cost best practices:
- LIMIT doesn't save money. The docs say that for tables that aren't clustered, a LIMIT clause doesn't change how much data is read.
- Preview for free. Table preview lets you look at rows at no charge.
- Set a cap. The maximum bytes billed setting makes a query fail, with no charge, if it would read more than your limit.
Before you run anything big, check the estimate the console shows. It tells you how many bytes the query will read.
Worked example: one dashboard query, two ways
Here's the math with assumed numbers. Your table sizes will differ.


Say your GA4 export holds 0.5 TiB of events. A dashboard tile runs a SELECT star across all of it, and it refreshes 40 times a month. That's 40 × 0.5 = 20 TiB read. Take off the free 1 TiB, and you pay for 19 TiB. At $6.25 per TiB, that's $118.75 a month for one tile.
Now rewrite it. Pick the three columns you need and read only the last 90 days of tables with _TABLE_SUFFIX. Say that cuts each run to 0.05 TiB. Now 40 runs read 2 TiB. Take off the free 1 TiB, and you pay for 1 TiB, or $6.25 a month.
The bigger lesson isn't the dollars. It's that SQL makes cost visible. A spreadsheet export never tells you what it scanned. A query does, before you run it.
How do you check a query before you trust it?
A query that runs is not a query that's right. I run five checks before any number leaves my screen.


Question -> Grain -> Tables -> Joins -> Sanity check
"Leads by "one row contacts, roll up match one number
channel" per lead" touches first to the CRM
- Count the rows at each step. Run the query with just the FROM and WHERE, and count. Then add each join and count again. If the count jumps after a join, you have a fan-out.
- Check the grain of the output. Ask what one row of your result means. If you can't say it in five words, the query isn't done.
- Match one number to a trusted source. Pick one month and one channel. Compare it to the CRM or ad platform. Small gaps are normal. Big ones mean a bug.
- Look for nulls. Count the rows where key columns are empty. Nulls fall out of joins and groups without warning.
- Read the edges. Look at the first and last date in the result. Time zones and partial months cause more wrong charts than bad logic.
What are the common SQL mistakes marketers make?
Joining before rolling up. This is the fan-out from query 6. It inflates revenue, deals and leads. Always roll up the many side first.
Counting rows instead of people. COUNT(*) counts rows. If a table has one row per event, you just counted events. Use COUNT(DISTINCT contact_id) when you mean people.
Filtering a LEFT JOIN in the WHERE. A filter on the right table in WHERE turns your LEFT JOIN into an inner join, and the rows with no match vanish. Put that filter in the ON clause.
Judging young cohorts. Last month's cohort hasn't had time to convert. Compare cohorts only once they're all old enough.
Mixing time zones. GA4 timestamps are in UTC. Your CRM may not be. Convert both to one zone before you compare days.
Copying a query without its grain. A query from a teammate works for their question. Check what one row means before you reuse it.
How should you use AI to write SQL?
AI tools are good at drafting SQL. They're bad at knowing your data. So give them what they can't see: table names, columns, the grain of each table and one example row. Then ask for the query.
Treat the draft like a junior analyst's work. Run the five checks above. Look hardest at joins and date filters, since that's where drafts go wrong. Over time, save the queries that pass into a shared folder or a dbt model, so nobody starts from a blank page.
Once your queries are trusted, the next step is to push the results back to the tools your team uses. My guide to reverse ETL for marketing covers how to send a warehouse number into the CRM and ad platforms.
What should you do this week?
If you'd rather have the warehouse, models and dashboards built for you, that's part of my GTM engineering service. The pipeline model use case shows the kind of numbers these queries feed.
My take: learn ten queries, not a language
You don't need to master SQL. You need ten patterns and the habit of checking your grain. That's a few weeks of short practice, and it changes how you work. You stop waiting for reports. You start asking better questions, because you know what the data can and can't say.
The marketers I trust most with numbers aren't the ones with the fanciest dashboards. They're the ones who can open the query and explain every line. Be that person. Start with query 2 today.
FAQ
How much SQL does a marketer need to know?
Less than you think. SELECT, WHERE, GROUP BY, JOIN, CASE WHEN and one window function cover most marketing questions. You can learn them in a few weeks of short practice. The harder skill is knowing the grain of each table, so your counts are right. That comes from reading your own data, not from a course.
Which SQL dialect should marketers learn?
Learn the one your warehouse uses, but don't worry much. PostgreSQL, BigQuery and Snowflake share the same core. The differences show up in date functions, text functions and a few shortcuts. Write the basics once, then look up the date syntax for your warehouse when you need it. The logic carries over.
Is SQL better than spreadsheets for marketing data?
For anything you run more than once, yes. A query is saved, repeatable and checkable, and it works on millions of rows. A spreadsheet is great for a quick look or for sharing a small result. Many teams do the heavy lifting in SQL and send a small summary table to a sheet.
Can a marketer break the warehouse by running a query?
Not with read-only access, which is what marketers should have. A SELECT query only reads data. The real risk is cost on usage-priced warehouses like BigQuery, where you pay for bytes read. Set a maximum bytes billed limit, avoid SELECT star and preview tables for free before you query them.
Can AI write SQL for me?
AI tools are good at drafting SQL if you give them your table names, columns and the grain of each table. Treat the draft as a first pass. Check the row counts, test it on a small date range and compare one number to a source you trust. The model can't see your data, so it can't catch a bad join.
Where does a marketer get a warehouse to practice on?
Ask your data or ops team for read-only access to the real one, ideally with a view built for marketing. If your company has none, BigQuery has a free monthly query allowance, and GA4 can export events to it. That gives you real data from your own site to practice on.