SQL for Marketers with AI
SQL for marketers means learning enough of SQL (Structured Query Language) to pull answers from marketing data yourself: leads from a CRM, orders from a store, or website events from BigQuery. A handful of commands, used together, answers most questions about which campaigns bring leads, demos and revenue.
- SELECT and FROM: Choose which columns to show and which table they come from.
- WHERE: Keep only the rows you need, such as leads from one city or one campaign.
- GROUP BY: Total the rows by source, city or campaign, so each group becomes one line.
- CASE: Count only the rows that meet a condition, such as leads that booked a demo.
- JOIN: Connect two tables that share an ID, such as leads and the deals they became.
This tutorial follows one example, a Bengaluru SaaS startup that sells HR and payroll software to small businesses. Leads come from Google Ads, LinkedIn and monthly webinars. Every lead is stored in a table, and closed deals are stored in another. The marketing lead wants to know which source brings demos and revenue, without waiting for the engineering team.
Until now, the team has pulled a spreadsheet from the CRM every Monday and built pivot tables by hand, which takes most of a morning and breaks whenever a column moves. Learning a few SQL queries lets the marketing lead ask the same questions directly, repeat them every week in seconds, and check the numbers that an agency or an AI tool reports back.
Prerequisites for SQL for Marketers
- Read access to data: A CRM export, a reporting database, or the GA4 BigQuery export.
- A place to run queries: The BigQuery console, a database tool your company already uses, or a small practice database on your laptop where mistakes cannot harm anything.
- Clean source values: Lead sources should be stored consistently, which starts with good UTM parameters.
- No personal data in practice files: Remove names, emails and phone numbers before you copy or share any table, even inside the company.
Setup: The Sample Tables
The startup's leads table (simplified to eight rows):
| lead_id | source | city | status |
|---|---|---|---|
| 1 | google_ads | Bengaluru | demo_booked |
| 2 | Pune | new | |
| 3 | google_ads | Chennai | demo_booked |
| 4 | webinar | Bengaluru | demo_booked |
| 5 | Bengaluru | demo_booked | |
| 6 | google_ads | Hyderabad | new |
| 7 | webinar | Pune | demo_booked |
| 8 | google_ads | Mumbai | demo_booked |
The deals table holds signed customers and their annual plan value in rupees:
| lead_id | plan | amount_inr |
|---|---|---|
| 1 | growth | 48000 |
| 4 | starter | 18000 |
| 5 | growth | 48000 |
| 8 | starter | 18000 |
These are sample rows made up for practice, so the numbers only show how each query works. In a real CRM the leads table would have thousands of rows and more columns, such as the date the lead arrived and the campaign name, but the queries below work in exactly the same way on a table of any size.
The two tables share one column, lead_id, and that shared column is what lets SQL connect a lead to the deal it became. Most marketing databases are built in the same way, with one table per kind of thing (leads, deals, ad costs, website events), linked by an ID that appears in both.
Step-by-Step: Five Queries Every Marketer Can Use
Step 1: Select and Filter Rows
Which leads came from Bengaluru?
SELECT lead_id, source, status
FROM leads
WHERE city = 'Bengaluru';| lead_id | source | status |
|---|---|---|
| 1 | google_ads | demo_booked |
| 4 | webinar | demo_booked |
| 5 | demo_booked |
- SELECT lists the columns to show, in the order you want them to appear.
- FROM names the table the rows come from, here the leads table.
- WHERE keeps only the rows that match the condition, and text values such as city names go inside single quotes.
Step 2: Count by Group
How many demos did each source bring?
SELECT source, COUNT(*) AS demos
FROM leads
WHERE status = 'demo_booked'
GROUP BY source
ORDER BY demos DESC;| source | demos |
|---|---|
| google_ads | 3 |
| webinar | 2 |
| 1 |
COUNT(*)counts the rows in each group, after WHERE has removed the leads that did not book a demo.- AS demos gives the result column a readable name that you can also use later in ORDER BY.
- GROUP BY makes one row per source. Every column in SELECT that is not a total must be in GROUP BY.
- ORDER BY ... DESC sorts the result so the largest total comes first, which makes the winner easy to spot.
Step 3: Count Conditions with CASE
How many leads and how many demos did each source bring, side by side?
SELECT
source,
COUNT(*) AS leads,
SUM(CASE WHEN status = 'demo_booked' THEN 1 ELSE 0 END) AS demos
FROM leads
GROUP BY source
ORDER BY source;| source | leads | demos |
|---|---|---|
| google_ads | 4 | 3 |
| 2 | 1 | |
| webinar | 2 | 2 |
CASE gives 1 for a demo and 0 for anything else, and SUM adds them up. Now the team can see that every webinar lead in the sample booked a demo, while Google Ads brought more leads in total. That difference matters for budget decisions, because a source that brings fewer leads can still be the better one if those leads turn into demos and customers more often.
Step 4: Join Leads to Deals
Which source brought the most revenue?
SELECT
l.source,
COUNT(d.lead_id) AS deals,
SUM(d.amount_inr) AS revenue_inr
FROM leads AS l
JOIN deals AS d
ON d.lead_id = l.lead_id
GROUP BY l.source
ORDER BY revenue_inr DESC;| source | deals | revenue_inr |
|---|---|---|
| google_ads | 2 | 66000 |
| 1 | 48000 | |
| webinar | 1 | 18000 |
- l and d are short names (aliases) for the two tables, which keep the query short and show which table each column comes from.
- JOIN ... ON keeps rows where the lead_id matches in both tables, so leads with no deal drop out of the result; use LEFT JOIN when you want to keep them.
Step 5: Turn Answers into Marketing Metrics
The same pattern answers the questions that matter: cost per demo (join an ad cost table by source), demo to deal rate, or revenue per lead. In the sample, Google Ads brought two of the four deals, but the team would need the ad cost for each source before calling it the best channel, because a source can win on revenue and still lose on cost. Compare cost per lead with cost per qualified lead, as explained in cost per qualified lead vs CPL.
Step 6: Save and Reuse
Save each working query with a comment at the top saying what it answers. Next month you only change the date filter. For recurring reports, save the result to a table and connect it to a dashboard.
Common Mistakes in SQL for Marketers
- Missing GROUP BY columns: Every column in SELECT that is not a total must also appear in GROUP BY, or most databases will refuse to run the query.
- Double quotes for text: Many databases read "Pune" as a column name rather than a value, so always use single quotes for text.
- Counting duplicates: If one lead appears in several rows,
COUNT(*)overcounts. UseCOUNT(DISTINCT lead_id). - Inner join surprises: A plain JOIN quietly drops every lead that has no deal, which hides the real conversion rate from anyone reading the result.
- Mixed-case values: Google_Ads and google_ads are treated as different values, so clean the data at the source or wrap the column in LOWER(source) when you group it.
- Running on the full table first: Test every new query on a small date range or add LIMIT, especially in BigQuery, where each scan of a large table costs money.
Next Steps
- Website data: Apply these patterns to raw events with the GA4 BigQuery export.
- Interpretation: Turn query results into decisions with analyze marketing data with AI.
- Scoring leads: Use demo and deal history as the base for predictive lead scoring.
How AI Changes SQL for Marketers
What AI Automates Now
AI assistants turn a plain question into a draft query when you give them the table and column names, explain error messages, and convert a query between dialects, such as MySQL to BigQuery. Many database tools now include an assistant that suggests SQL inside the editor.
What Still Needs a Human
Marketers still decide what the question means: what counts as a qualified lead, which date to use, whether a lead from two sources counts twice. Reading the query and checking its result against a known total stays with you.
Risk to Watch
AI can write SQL that runs without errors but answers a different question, for example counting rows instead of unique leads, and it can also invent column names that do not exist in your tables. See why in AI hallucinations, and check every new query on a small sample you can count by hand.
Do It with AI
Use this prompt to draft a query. It works in ChatGPT, Claude or Gemini, and you should share only table and column names, never real rows with personal data.
You are a SQL tutor helping a marketer. Database: [BigQuery, PostgreSQL or MySQL] Tables and columns: [for example, leads(lead_id, source, city, status), deals(lead_id, plan, amount_inr)] Question: [for example, demo to deal rate by source] 1. Write one SQL query that answers the question, using only the tables and columns listed. 2. Explain each clause in one simple sentence. 3. Tell me how to test it on a small sample and what result would prove it is right. 4. Point out any business definition I need to decide, such as how to treat duplicate leads. If a column I need is missing, say so instead of inventing one.
- List your real table and column names in the prompt.
- Run the query with LIMIT or on one week of data.
- Count a few rows by hand and compare with the result.
- Save the query with a comment once it matches.
Check Before You Use It
- Facts: Every column and table name must exist in your database; check the result against a total you already trust.
- Brand fit: Use the team's definitions of lead, demo and deal, not the AI's guess.
- Compliance: Share schemas, not data. Never paste rows with names, emails or phone numbers into an AI tool.
Quick Quiz
Pick an answer to check yourself. Nothing is saved.
Question 1 / 3
1. The startup wants only leads from Pune. Which clause filters rows?
Frequently Asked Questions
Do marketers really need to learn SQL?
Not every marketer, but it helps anyone who works with leads, orders or website data. Basic SQL lets you answer your own questions from a CRM or BigQuery without waiting for an analyst, and lets you check AI-written queries.
How long does it take to learn basic SQL?
The five clauses in this lesson (SELECT, FROM, WHERE, GROUP BY and ORDER BY) plus JOIN and CASE cover most marketing questions. Many people learn them in a few weeks of short practice on their own data.
Can AI write SQL for me?
Yes. AI assistants write good first drafts when you give them the table and column names. You still need to read the query, run it on a small sample and check the result, because AI can use wrong column names or count the wrong thing.
Which SQL should I learn: MySQL, PostgreSQL or BigQuery?
The basics in this lesson work in all of them. Small differences appear in date functions and some advanced features. Learn the dialect your company's data lives in; for GA4 raw data that is BigQuery.
Related Articles
- GA4 BigQuery ExportGA4 BigQuery export tutorial: link your property, learn the events tables and run your first SQL queries on raw data, with an Indore snack brand example.
- Analyze Marketing Data with AIAnalyze marketing data with AI safely: a five-step framework, a checklist, and how to verify every number, shown with a Hyderabad kirana store example.
- UTM ParametersUTM parameters explained: the five tags, a naming convention template and real link examples, so every Diwali sale click lands in the right GA4 channel.
- What is CRM in MarketingWhat is CRM in marketing? Learn how a CRM stores customer data, powers reminders and campaigns, and where AI helps, with a Hyderabad dental clinic example.
- Cost per Qualified Lead vs CPLCost per qualified lead vs CPL compared with a worked rupee example, so you can see which lead source really pays and judge campaigns by lead quality.
- Predictive Lead Scoring with AIPredictive lead scoring explained: how points and AI models rank leads so sales calls the right people first, with a worked Ahmedabad rooftop solar case.