Marketing Analytics t ≈ 20 min

SQL Markdown for Marketing Analysts: Build AI-Ready Data Instructions That Query Any Dataset

Marketing analysts build markdown files with SQL instructions that AI tools query automatically. Connect spreadsheets, Snowflake, and databases to Claude.

yfx(m)

yfxmarketer

December 30, 2025

Marketing analysts spend 60% of their time writing the same SQL queries. Campaign performance by channel. Cohort retention rates. Attribution touchpoints. Revenue by segment. The queries repeat. The data sources change. The context gets lost between requests.

Markdown files with embedded SQL instructions solve this problem permanently. You write the query once with clear documentation. AI assistants read the markdown and execute the query against any connected data source. Claude with Skills, Snowflake Cortex, and database-connected AI tools all consume the same instruction format. One markdown file powers unlimited analysis requests.

TL;DR

Marketing analysts create markdown files containing SQL queries, schema documentation, and usage instructions. AI assistants read these files and execute queries against connected databases, spreadsheets, or data warehouses. Claude Skills extend this pattern into reusable analysis capabilities. The investment is writing queries once. The return is instant analysis on demand, forever. This guide provides complete templates, working examples, and step-by-step instructions for building your own SQL markdown library.

Key Takeaways

  • Markdown files with SQL instructions become reusable assets AI assistants execute on demand
  • Schema documentation in markdown eliminates repeated explanations of table structures
  • Claude Skills package multiple SQL markdowns into domain-specific analysis capabilities
  • The same markdown format works across spreadsheets, Snowflake, BigQuery, and PostgreSQL
  • Query libraries compound value as you add more analysis patterns over time
  • AI assistants interpret natural language requests and select the appropriate SQL from your library
  • Marketing teams without SQL skills request analysis using plain English once markdowns exist

What Is SQL Markdown and Why Do Marketing Analysts Need It?

SQL markdown combines query code with human-readable documentation in a single file. The markdown explains what the query does, when to use it, and what parameters to customize. AI assistants parse both the documentation and the SQL to understand how and when to execute each query.

Traditional SQL lives in database tools, scattered scripts, or tribal knowledge. Finding the right query requires asking colleagues or searching through undocumented files. SQL markdown creates a searchable, self-documenting library that AI assistants navigate automatically.

How Do AI Assistants Use SQL Markdown Files?

AI assistants read markdown files as context for analysis requests. When you ask “show me campaign performance by channel for Q4,” the AI scans your SQL markdown library, finds the relevant query, substitutes parameters, and executes against your connected data source.

The AI handles parameter substitution, date range calculation, and output formatting. You describe what you want in plain English. The markdown provides the technical implementation. The AI bridges the gap between business questions and database queries.

What Data Sources Work with SQL Markdown?

SQL markdown works with any data source that accepts SQL queries. Snowflake, BigQuery, PostgreSQL, MySQL, and Redshift all execute standard SQL. Spreadsheet tools like Google Sheets accept SQL through connected databases or query functions.

Claude’s MCP (Model Context Protocol) connectors link directly to Snowflake and other databases. Upload a CSV and Claude queries it using SQL syntax. The markdown format stays consistent regardless of the underlying data source.

Action item: List the three data sources your marketing team queries most frequently. Identify which support direct SQL access and which require export to spreadsheets first.

How Do You Structure a SQL Markdown File?

SQL markdown files follow a consistent structure that AI assistants parse reliably. Each file contains metadata, schema documentation, query code, usage examples, and parameter definitions. This structure enables AI to select and execute the right query for any request.

The Core Components of SQL Markdown

Every SQL markdown file needs these sections to function with AI assistants:

  • Title and Description: What analysis this query performs
  • Schema Reference: Tables and columns the query uses
  • Parameters: Variables the user or AI customizes per request
  • SQL Query: The actual code with parameter placeholders
  • Usage Examples: Sample requests that trigger this query
  • Output Format: What the results look like

Basic SQL Markdown Template

Use this template as the starting point for every SQL markdown file:

# Query Name: Campaign Performance by Channel

## Description
Returns campaign performance metrics grouped by marketing channel for a specified date range. Use this query to compare channel effectiveness and identify top performers.

## When to Use
- Monthly channel performance reviews
- Budget allocation decisions
- Campaign retrospectives
- Executive reporting on marketing mix

## Schema Reference

### Table: campaigns
| Column | Type | Description |
|--------|------|-------------|
| campaign_id | STRING | Unique campaign identifier |
| campaign_name | STRING | Human-readable campaign name |
| channel | STRING | Marketing channel (email, paid_search, social, etc.) |
| start_date | DATE | Campaign launch date |
| end_date | DATE | Campaign end date |
| budget | FLOAT | Allocated budget in USD |

### Table: campaign_metrics
| Column | Type | Description |
|--------|------|-------------|
| campaign_id | STRING | Foreign key to campaigns |
| date | DATE | Metric date |
| impressions | INT | Total impressions |
| clicks | INT | Total clicks |
| conversions | INT | Total conversions |
| spend | FLOAT | Actual spend in USD |
| revenue | FLOAT | Attributed revenue in USD |

## Parameters

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| {{START_DATE}} | DATE | Yes | None | Beginning of date range |
| {{END_DATE}} | DATE | Yes | None | End of date range |
| {{CHANNELS}} | LIST | No | All | Filter to specific channels |

## SQL Query

```sql
SELECT 
    c.channel,
    COUNT(DISTINCT c.campaign_id) AS total_campaigns,
    SUM(m.impressions) AS total_impressions,
    SUM(m.clicks) AS total_clicks,
    SUM(m.conversions) AS total_conversions,
    SUM(m.spend) AS total_spend,
    SUM(m.revenue) AS total_revenue,
    ROUND(SUM(m.clicks) / NULLIF(SUM(m.impressions), 0) * 100, 2) AS ctr_percent,
    ROUND(SUM(m.conversions) / NULLIF(SUM(m.clicks), 0) * 100, 2) AS conversion_rate,
    ROUND(SUM(m.revenue) / NULLIF(SUM(m.spend), 0), 2) AS roas
FROM campaigns c
JOIN campaign_metrics m ON c.campaign_id = m.campaign_id
WHERE m.date BETWEEN '{{START_DATE}}' AND '{{END_DATE}}'
    AND ({{CHANNELS}} IS NULL OR c.channel IN ({{CHANNELS}}))
GROUP BY c.channel
ORDER BY total_revenue DESC;

Usage Examples

Request: “Show me channel performance for Q4 2024” Parameters: START_DATE = ‘2024-10-01’, END_DATE = ‘2024-12-31’

Request: “Compare email and paid search performance last month” Parameters: START_DATE = ‘2024-11-01’, END_DATE = ‘2024-11-30’, CHANNELS = (‘email’, ‘paid_search’)

Request: “Which channel had the best ROAS this year?” Parameters: START_DATE = ‘2024-01-01’, END_DATE = ‘2024-12-31’

Output Format

channeltotal_campaignstotal_impressionstotal_clickstotal_conversionstotal_spendtotal_revenuectr_percentconversion_rateroas
paid_search452,500,00075,0003,200125,000480,0003.004.273.84
email120800,00048,0002,80015,000210,0006.005.8314.00

Action item: Create your first SQL markdown file using this template. Choose your most frequently requested analysis query. Document the schema, parameters, and usage examples completely.

What Are the Essential SQL Queries Every Marketing Analyst Should Document?

Marketing analysis revolves around a core set of recurring queries. Documenting these queries in markdown creates a foundation that covers 80% of analysis requests. Start with these essential patterns and expand based on your team’s specific needs.

Campaign Performance Queries

Campaign performance queries answer the fundamental question: how are our marketing efforts performing? These queries aggregate metrics across campaigns, channels, and time periods.

Use this prompt to generate a campaign performance SQL markdown:

SYSTEM: You are a marketing analytics engineer who writes SQL for data warehouses.

<context>
Data warehouse: {{SNOWFLAKE_OR_BIGQUERY}}
Campaign table: {{CAMPAIGN_TABLE_NAME}}
Metrics table: {{METRICS_TABLE_NAME}}
Date column: {{DATE_COLUMN}}
</context>

Create a SQL markdown file for campaign performance analysis.

MUST include:
1. Full schema documentation with column types
2. Query with parameters for date range and channel filter
3. Calculated metrics: CTR, conversion rate, CPA, ROAS
4. Three usage example requests with parameter values
5. Sample output table

MUST follow these rules:
- Use NULLIF to prevent division by zero
- Round percentages to 2 decimal places
- Order results by revenue descending
- Include campaign count per group

Output: Complete markdown file ready to save.

Cohort Retention Queries

Cohort retention queries track how user groups behave over time. Marketing teams use cohorts to measure campaign quality, identify churn patterns, and calculate lifetime value.

Use this prompt to generate a cohort retention SQL markdown:

SYSTEM: You are a marketing analytics engineer specializing in cohort analysis.

<context>
User table: {{USER_TABLE}}
Event table: {{EVENT_TABLE}}
Signup date column: {{SIGNUP_DATE_COLUMN}}
Activity date column: {{ACTIVITY_DATE_COLUMN}}
Cohort granularity: {{WEEKLY_OR_MONTHLY}}
</context>

Create a SQL markdown file for cohort retention analysis.

MUST include:
1. Schema documentation for user and event tables
2. Query that creates cohorts by signup period
3. Retention calculation for periods 0 through 12
4. Pivot format showing cohort rows and period columns
5. Parameters for cohort start date and end date

MUST calculate:
- Cohort size (period 0 users)
- Retained users per period
- Retention percentage per period

Output: Complete markdown file with CTE-based query structure.

# Cohort retention is the percentage of users who return in each subsequent period

Attribution Analysis Queries

Attribution queries assign credit for conversions across marketing touchpoints. First-touch, last-touch, and multi-touch models require different SQL patterns.

Use this prompt to generate an attribution SQL markdown:

SYSTEM: You are a marketing analytics engineer who builds attribution models.

<context>
Touchpoint table: {{TOUCHPOINT_TABLE}}
Conversion table: {{CONVERSION_TABLE}}
User ID column: {{USER_ID_COLUMN}}
Timestamp column: {{TIMESTAMP_COLUMN}}
Attribution model: {{FIRST_TOUCH_OR_LAST_TOUCH_OR_LINEAR}}
</context>

Create a SQL markdown file for marketing attribution analysis.

MUST include:
1. Schema for touchpoint and conversion tables
2. Query implementing the specified attribution model
3. Parameters for date range and conversion event type
4. Aggregation by channel and campaign
5. Revenue and conversion attribution totals

MUST handle:
- Users with single touchpoint (100% credit)
- Users with multiple touchpoints (model-specific distribution)
- Conversions without prior touchpoints (direct/organic)

Output: Complete markdown file with window functions for touchpoint ordering.

Funnel Analysis Queries

Funnel queries track conversion through sequential steps. Marketing funnels measure landing page to signup, trial to paid, or awareness to purchase progressions.

Use this prompt to generate a funnel analysis SQL markdown:

SYSTEM: You are a marketing analytics engineer who builds conversion funnels.

<context>
Event table: {{EVENT_TABLE}}
User ID column: {{USER_ID_COLUMN}}
Event name column: {{EVENT_NAME_COLUMN}}
Timestamp column: {{TIMESTAMP_COLUMN}}
Funnel steps: {{STEP_1}}, {{STEP_2}}, {{STEP_3}}, {{STEP_4}}
</context>

Create a SQL markdown file for funnel conversion analysis.

MUST include:
1. Schema documentation for event table
2. Query that counts users at each funnel step
3. Step-to-step conversion rates
4. Overall funnel conversion rate
5. Parameters for date range and user segment

MUST calculate:
- Users entering each step
- Drop-off count between steps
- Drop-off percentage between steps
- Time between steps (if timestamp available)

Output: Complete markdown file with sequential step filtering.

# Funnel requires users to complete steps in order within the date range

Action item: Generate SQL markdown files for the four query types above using the prompts provided. Customize the context variables for your actual table names and column structures.

How Do You Build a Claude Skill from SQL Markdowns?

Claude Skills package multiple SQL markdown files into a cohesive analysis capability. A single Skill contains schema documentation, query library, and usage instructions that Claude references when you request analysis. Skills turn your SQL markdowns into a reusable AI-powered analyst.

What Is a Claude Skill?

A Claude Skill is a markdown file (SKILL.md) that teaches Claude how to perform a specific task. For SQL analysis, the Skill file explains available queries, data sources, and analysis patterns. Claude reads the Skill before responding to your requests.

Skills live in the /mnt/skills/ directory structure in Claude’s environment. You create Skills by uploading markdown files to a Claude Project or by placing them in the skills folder when using Claude Code.

Claude Skill Structure for SQL Analysis

A SQL analysis Skill contains these components:

  • Skill Overview: What analysis capabilities this Skill provides
  • Data Source Configuration: How to connect to databases or spreadsheets
  • Schema Reference: All tables and columns available for querying
  • Query Library: Links or embedded SQL for common analysis patterns
  • Usage Instructions: How to request analysis using this Skill

Complete Claude Skill Template for Marketing Analytics

Save this as SKILL.md in your skills folder:

# Marketing Analytics SQL Skill

## Overview

This skill enables Claude to perform marketing analytics queries against connected data sources. Claude reads this file to understand available tables, query patterns, and analysis capabilities.

## Capabilities

- Campaign performance analysis by channel, time period, and segment
- Cohort retention calculations with customizable periods
- Marketing attribution across touchpoints
- Funnel conversion analysis
- Revenue and ROI calculations
- Custom SQL query generation

## Data Source Configuration

### Snowflake Connection
When connected via MCP Snowflake connector:
- Database: MARKETING_DW
- Schema: ANALYTICS
- Role: MARKETING_ANALYST

### Spreadsheet Analysis
When analyzing uploaded CSV/Excel files:
- Claude executes SQL using DuckDB syntax
- Upload files are available as tables named after the filename
- Example: `campaign_data.csv` becomes table `campaign_data`

## Schema Reference

### campaigns
Primary table for campaign metadata.

| Column | Type | Description | Example |
|--------|------|-------------|---------|
| campaign_id | VARCHAR | Unique identifier | "camp_2024_q4_001" |
| campaign_name | VARCHAR | Display name | "Q4 Holiday Sale" |
| channel | VARCHAR | Marketing channel | "paid_search" |
| sub_channel | VARCHAR | Channel subdivision | "google_brand" |
| start_date | DATE | Launch date | 2024-10-01 |
| end_date | DATE | End date | 2024-12-31 |
| budget | DECIMAL(12,2) | Allocated budget USD | 50000.00 |
| objective | VARCHAR | Campaign goal | "conversions" |
| target_audience | VARCHAR | Audience segment | "returning_customers" |

### campaign_metrics_daily
Daily performance metrics per campaign.

| Column | Type | Description | Example |
|--------|------|-------------|---------|
| campaign_id | VARCHAR | Foreign key to campaigns | "camp_2024_q4_001" |
| date | DATE | Metric date | 2024-10-15 |
| impressions | INT | Ad impressions | 125000 |
| clicks | INT | Ad clicks | 3750 |
| conversions | INT | Conversion events | 188 |
| spend | DECIMAL(12,2) | Daily spend USD | 1250.00 |
| revenue | DECIMAL(12,2) | Attributed revenue USD | 9400.00 |

### users
User profile and acquisition data.

| Column | Type | Description | Example |
|--------|------|-------------|---------|
| user_id | VARCHAR | Unique user identifier | "usr_abc123" |
| signup_date | DATE | Account creation date | 2024-06-15 |
| acquisition_channel | VARCHAR | First touch channel | "organic_search" |
| acquisition_campaign | VARCHAR | First touch campaign | "camp_2024_q2_seo" |
| country | VARCHAR | User country | "US" |
| plan_type | VARCHAR | Subscription tier | "premium" |

### events
User behavioral events.

| Column | Type | Description | Example |
|--------|------|-------------|---------|
| event_id | VARCHAR | Unique event identifier | "evt_xyz789" |
| user_id | VARCHAR | Foreign key to users | "usr_abc123" |
| event_name | VARCHAR | Event type | "purchase" |
| event_timestamp | TIMESTAMP | Event occurrence time | 2024-10-15 14:30:00 |
| properties | VARIANT | Event metadata JSON | {"amount": 99.00} |

## Query Patterns

### Pattern 1: Channel Performance Summary

Use when asked about channel comparison, channel effectiveness, or marketing mix.

```sql
SELECT 
    c.channel,
    COUNT(DISTINCT c.campaign_id) AS campaigns,
    SUM(m.impressions) AS impressions,
    SUM(m.clicks) AS clicks,
    SUM(m.conversions) AS conversions,
    SUM(m.spend) AS spend,
    SUM(m.revenue) AS revenue,
    ROUND(SUM(m.clicks) * 100.0 / NULLIF(SUM(m.impressions), 0), 2) AS ctr,
    ROUND(SUM(m.conversions) * 100.0 / NULLIF(SUM(m.clicks), 0), 2) AS cvr,
    ROUND(SUM(m.spend) / NULLIF(SUM(m.conversions), 0), 2) AS cpa,
    ROUND(SUM(m.revenue) / NULLIF(SUM(m.spend), 0), 2) AS roas
FROM campaigns c
JOIN campaign_metrics_daily m ON c.campaign_id = m.campaign_id
WHERE m.date BETWEEN {{start_date}} AND {{end_date}}
GROUP BY c.channel
ORDER BY revenue DESC;

Pattern 2: Weekly Cohort Retention

Use when asked about retention, cohort analysis, or user engagement over time.

WITH cohorts AS (
    SELECT 
        user_id,
        DATE_TRUNC('week', signup_date) AS cohort_week
    FROM users
    WHERE signup_date BETWEEN {{start_date}} AND {{end_date}}
),
activity AS (
    SELECT DISTINCT
        user_id,
        DATE_TRUNC('week', event_timestamp) AS activity_week
    FROM events
    WHERE event_name = {{retention_event}}
)
SELECT 
    c.cohort_week,
    COUNT(DISTINCT c.user_id) AS cohort_size,
    COUNT(DISTINCT CASE WHEN DATEDIFF('week', c.cohort_week, a.activity_week) = 0 THEN c.user_id END) AS week_0,
    COUNT(DISTINCT CASE WHEN DATEDIFF('week', c.cohort_week, a.activity_week) = 1 THEN c.user_id END) AS week_1,
    COUNT(DISTINCT CASE WHEN DATEDIFF('week', c.cohort_week, a.activity_week) = 2 THEN c.user_id END) AS week_2,
    COUNT(DISTINCT CASE WHEN DATEDIFF('week', c.cohort_week, a.activity_week) = 3 THEN c.user_id END) AS week_3,
    COUNT(DISTINCT CASE WHEN DATEDIFF('week', c.cohort_week, a.activity_week) = 4 THEN c.user_id END) AS week_4
FROM cohorts c
LEFT JOIN activity a ON c.user_id = a.user_id
GROUP BY c.cohort_week
ORDER BY c.cohort_week;

Pattern 3: Last-Touch Attribution

Use when asked about attribution, conversion credit, or channel contribution.

WITH touchpoints AS (
    SELECT 
        user_id,
        event_timestamp,
        properties:channel::VARCHAR AS channel,
        properties:campaign::VARCHAR AS campaign,
        ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY event_timestamp DESC) AS touch_rank
    FROM events
    WHERE event_name = 'ad_click'
),
conversions AS (
    SELECT 
        user_id,
        event_timestamp AS conversion_time,
        properties:revenue::DECIMAL(12,2) AS revenue
    FROM events
    WHERE event_name = 'purchase'
    AND event_timestamp BETWEEN {{start_date}} AND {{end_date}}
)
SELECT 
    t.channel,
    t.campaign,
    COUNT(*) AS conversions,
    SUM(c.revenue) AS attributed_revenue
FROM conversions c
JOIN touchpoints t ON c.user_id = t.user_id 
    AND t.touch_rank = 1
    AND t.event_timestamp < c.conversion_time
GROUP BY t.channel, t.campaign
ORDER BY attributed_revenue DESC;

Usage Instructions

When a user asks for marketing analysis:

  1. Identify which query pattern matches the request
  2. Determine required parameters (date range, filters, segments)
  3. If parameters are unclear, ask for clarification
  4. Execute the query against the connected data source
  5. Format results as a clear table with insights
  6. Offer follow-up analysis options

Example Requests and Responses

Request: “How did our channels perform in Q4?” Action: Execute Pattern 1 with start_date=‘2024-10-01’, end_date=‘2024-12-31’

Request: “Show me retention for users who signed up in November” Action: Execute Pattern 2 with start_date=‘2024-11-01’, end_date=‘2024-11-30’, retention_event=‘login’

Request: “Which campaigns drove the most revenue last month?” Action: Execute Pattern 3 with start_date=‘2024-11-01’, end_date=‘2024-11-30’

Limitations

  • Queries assume Snowflake SQL syntax by default
  • Date parameters must be in YYYY-MM-DD format
  • Revenue figures are in USD unless specified
  • Cohort analysis limited to 12 periods for readability

Extending This Skill

To add new query patterns:

  1. Document the use case in plain language
  2. Add schema for any new tables required
  3. Write the SQL with parameter placeholders
  4. Include example requests that trigger the query
  5. Test with sample data before production use

Action item: Create a Claude Project and upload this SKILL.md file. Test it by asking Claude to analyze sample marketing data you upload as a CSV.

How Do You Connect SQL Markdown to Live Data Sources?

SQL markdown files need data connections to execute queries. Connection methods vary by data source and AI tool. Claude supports MCP connectors for databases and direct file analysis for spreadsheets.

Connecting Claude to Snowflake via MCP

Claude’s MCP (Model Context Protocol) enables direct database connections. The Snowflake MCP connector lets Claude execute SQL queries against your data warehouse without data exports.

To configure Snowflake MCP:

  1. Enable MCP in Claude settings
  2. Add Snowflake connector with credentials
  3. Specify database, schema, and role permissions
  4. Test connection with a simple query

Once connected, Claude reads your SQL markdowns and executes queries directly against Snowflake. Results return in the conversation for immediate analysis.

Analyzing Spreadsheet Data with SQL

Claude analyzes uploaded CSV and Excel files using SQL syntax. Upload a file and Claude treats it as a queryable table. The filename becomes the table name.

Use this prompt to analyze spreadsheet data with SQL:

SYSTEM: You are a marketing analyst who writes SQL queries for spreadsheet data.

I uploaded a file called {{FILENAME}}.

<analysis_request>
{{WHAT_I_WANT_TO_KNOW}}
</analysis_request>

Write and execute a SQL query to answer this question.

MUST:
1. Reference the uploaded file as table "{{TABLE_NAME}}"
2. Use DuckDB-compatible SQL syntax
3. Handle NULL values appropriately
4. Format numeric results with appropriate precision
5. Explain what the query does before showing results

Output: SQL query, then results table, then 2-3 key insights.

Building a Local Query Library

Store SQL markdown files in a GitHub repository or local folder. Organize by analysis type:

sql-markdowns/
├── campaign-performance/
│   ├── channel-summary.md
│   ├── campaign-detail.md
│   └── daily-trends.md
├── cohort-analysis/
│   ├── weekly-retention.md
│   ├── monthly-retention.md
│   └── ltv-by-cohort.md
├── attribution/
│   ├── first-touch.md
│   ├── last-touch.md
│   └── linear-attribution.md
└── funnel/
    ├── signup-funnel.md
    ├── purchase-funnel.md
    └── activation-funnel.md

Upload relevant markdowns to Claude Projects for persistent access. Claude references the library when you request analysis.

Action item: Create a folder structure for your SQL markdowns following the pattern above. Move your existing queries into the appropriate categories. Commit to GitHub for version control.

How Do You Write SQL Markdown for Non-Technical Team Members?

SQL markdowns serve two audiences: AI assistants that execute queries and team members who request analysis. Writing for non-technical users requires clear descriptions, plain-language examples, and output explanations.

Document Business Context, Not Technical Details

Non-technical users care about business questions, not JOIN syntax. Frame each query around the question it answers, not the tables it queries.

Instead of: “This query joins campaigns and campaign_metrics_daily on campaign_id”

Write: “This query shows how each marketing channel performed, including impressions, clicks, conversions, and return on ad spend”

Include Natural Language Request Examples

Show team members exactly how to ask for this analysis. Use the language they already use in Slack and meetings.

## How to Request This Analysis

Ask Claude any of these questions:
- "How did our campaigns perform last quarter?"
- "Which channel has the best ROAS?"
- "Compare email vs paid search performance"
- "Show me campaign metrics by channel for October"
- "What's our cost per acquisition by channel?"

Explain Output Columns in Plain Language

Define every column in the output table. Use business terms, not technical names.

## Understanding the Results

| Column | What It Means |
|--------|---------------|
| channel | The marketing channel (email, paid search, social, etc.) |
| campaigns | Number of campaigns run in this channel |
| spend | Total money spent on ads in USD |
| revenue | Total revenue attributed to this channel |
| ctr | Click-through rate: percentage of people who clicked after seeing the ad |
| cvr | Conversion rate: percentage of clickers who converted |
| cpa | Cost per acquisition: how much you paid for each conversion |
| roas | Return on ad spend: revenue divided by spend (higher is better) |

Create a Request Template for Common Analyses

Give team members a fill-in-the-blank template for requesting analysis:

## Request Template

Copy this template and fill in the blanks:

"Show me [METRIC] for [CHANNEL/CAMPAIGN/SEGMENT] 
from [START DATE] to [END DATE]
grouped by [TIME PERIOD: day/week/month]
filtered to [OPTIONAL: specific conditions]"

### Examples:

"Show me revenue for paid search from October 1 to December 31 grouped by week"

"Show me conversion rate for email campaigns from Q4 filtered to US customers only"

"Show me ROAS for all channels from 2024 grouped by month"

Action item: Review your existing SQL markdowns and add a “How to Request This Analysis” section to each one. Include 5+ natural language examples that match how your team actually asks for data.

How Do You Iterate and Improve SQL Markdowns Over Time?

SQL markdowns improve through usage. Track which queries get requested most. Note where AI misinterprets requests. Add new patterns when recurring questions lack coverage.

Log Analysis Requests and Outcomes

Keep a simple log of analysis requests and how well the SQL markdown performed:

## Query Performance Log

| Date | Request | Query Used | Outcome | Improvement Needed |
|------|---------|------------|---------|-------------------|
| 2024-12-15 | "Q4 channel performance" | channel-summary.md | Success | None |
| 2024-12-16 | "Show me email vs SMS" | channel-summary.md | Partial | Add SMS as channel option |
| 2024-12-17 | "Weekly revenue trends" | None | Failed | Create new query for time series |

Add New Queries Based on Gaps

When requests fail or require manual SQL writing, create new markdown files. Each gap represents a missing capability in your library.

Use this prompt to generate new SQL markdowns from failed requests:

SYSTEM: You are a marketing analytics engineer who documents SQL queries.

<context>
Failed request: "{{THE_REQUEST_THAT_FAILED}}"
Available tables: {{LIST_YOUR_TABLES}}
Existing queries: {{WHAT_YOU_ALREADY_HAVE}}
</context>

Create a new SQL markdown file that handles this request type.

MUST include:
1. Clear description of what this query answers
2. Schema reference for tables used
3. SQL with parameter placeholders
4. 5 natural language request examples
5. Output column explanations

MUST NOT duplicate existing query patterns. This fills a gap.

Output: Complete markdown file ready to add to the library.

Version Control Your Query Library

Store SQL markdowns in Git for version history. When queries change, commit with descriptive messages explaining why.

git commit -m "fix(channel-summary): handle NULL impressions in CTR calculation"
git commit -m "feat(attribution): add linear attribution model query"
git commit -m "docs(cohort): add business context for retention metrics"

Version control lets you roll back broken queries and track how your analysis capabilities evolved over time.

Action item: Set up a Git repository for your SQL markdown library. Commit your existing files with an initial commit. Establish a weekly review to add new queries based on that week’s analysis gaps.

What Are Advanced Patterns for SQL Markdown Power Users?

Advanced SQL markdown patterns handle complex analysis scenarios. Dynamic query generation, conditional logic, and multi-step analysis extend what your markdown library can accomplish.

Dynamic Date Range Calculation

Replace hardcoded dates with dynamic calculations. AI assistants interpret relative dates and substitute the correct values.

## Dynamic Date Parameters

This query supports these date range shortcuts:

| Request | START_DATE | END_DATE |
|---------|------------|----------|
| "last week" | Monday of previous week | Sunday of previous week |
| "last month" | First of previous month | Last of previous month |
| "last quarter" | First of previous quarter | Last of previous quarter |
| "MTD" | First of current month | Yesterday |
| "YTD" | January 1 of current year | Yesterday |
| "last 30 days" | 30 days ago | Yesterday |
| "last 90 days" | 90 days ago | Yesterday |

### SQL for Date Calculation (Snowflake)

```sql
-- Last week
WHERE date BETWEEN DATE_TRUNC('week', DATEADD('week', -1, CURRENT_DATE())) 
    AND DATEADD('day', -1, DATE_TRUNC('week', CURRENT_DATE()))

-- Last month
WHERE date BETWEEN DATE_TRUNC('month', DATEADD('month', -1, CURRENT_DATE())) 
    AND DATEADD('day', -1, DATE_TRUNC('month', CURRENT_DATE()))

-- Last 30 days
WHERE date BETWEEN DATEADD('day', -30, CURRENT_DATE()) AND DATEADD('day', -1, CURRENT_DATE())
```

Conditional Query Sections

Some analyses require different SQL based on user parameters. Document conditional logic for AI to follow.

## Conditional Query Logic

### If grouping by DAY:
```sql
SELECT DATE_TRUNC('day', date) AS period, ...
GROUP BY DATE_TRUNC('day', date)
```

### If grouping by WEEK:
```sql
SELECT DATE_TRUNC('week', date) AS period, ...
GROUP BY DATE_TRUNC('week', date)
```

### If grouping by MONTH:
```sql
SELECT DATE_TRUNC('month', date) AS period, ...
GROUP BY DATE_TRUNC('month', date)
```

Claude selects the appropriate version based on the user’s request.

Multi-Step Analysis Workflows

Complex analyses require multiple queries in sequence. Document the workflow for AI to follow.

Multi-Step: Campaign Optimization Analysis

This analysis requires three sequential queries:

Step 1: Identify Underperforming Campaigns

Find campaigns with ROAS below target.

SELECT campaign_id, campaign_name, channel, roas
FROM campaign_performance_view
WHERE roas < {{target_roas}}
AND date BETWEEN {{start_date}} AND {{end_date}};

Step 2: Analyze Daily Patterns

For each underperforming campaign, check daily performance.

SELECT date, impressions, clicks, conversions, spend, revenue
FROM campaign_metrics_daily
WHERE campaign_id = {{campaign_id_from_step_1}}
ORDER BY date;

Step 3: Compare to Successful Campaigns

Find similar campaigns that succeeded.

SELECT campaign_id, campaign_name, roas, budget, target_audience
FROM campaigns c
JOIN campaign_performance_view p ON c.campaign_id = p.campaign_id
WHERE c.channel = {{channel_from_step_1}}
AND p.roas >= {{target_roas}}
AND c.start_date >= DATEADD('month', -3, CURRENT_DATE());

Synthesis

After running all three steps, summarize findings:

  • Which campaigns underperformed
  • What patterns appear in their daily data
  • What successful campaigns did differently
  • Recommended optimizations

Action item: Identify your most complex recurring analysis. Break it into sequential steps. Document each step’s SQL and the synthesis logic. Test with Claude to verify the multi-step workflow executes correctly.

Final Takeaways

SQL markdown files transform one-time queries into permanent analysis assets. Write the query once, document it thoroughly, and AI assistants execute it forever.

Claude Skills package multiple SQL markdowns into domain-specific analysis capabilities. Marketing teams get instant answers without writing SQL themselves.

The same markdown format works across Snowflake, BigQuery, spreadsheets, and any SQL-compatible data source. Your documentation investment transfers between tools.

Start with the four essential query types: campaign performance, cohort retention, attribution, and funnel analysis. These patterns cover 80% of marketing analysis requests.

Iterate based on usage. Log failed requests. Fill gaps with new markdowns. Version control everything. Your query library compounds in value with every addition.

yfx(m)

yfxmarketer

AI Growth Operator

Writing about AI marketing, growth, and the systems behind successful campaigns.

read_next(related)