# Analytics SQL

> Readable analytics queries you can trust.

Analytics SQL is an agent skill from the Data & SQL collection on ProSkills, for Claude Code, Cursor, Codex and Gemini CLI. Your agent loads it when the user writes a report, metric or analytics query.

## Facts

- Price: Free (MIT, no account)
- Collection: [Data & SQL](https://proskills.dev/library/data-sql)
- Scan score: 100/100 (grade A) on the ProSkills scanner: spec, token efficiency, clarity and security
- Context cost: about 1,812 tokens when it triggers
- Files: 3
- Version: 1.0.0 (updated 2026-10-16)
- Rules: 5
- Page: https://proskills.dev/skills/analytics-sql

## Install

```bash
npx proskills-cli add analytics-sql
```

It detects your agent; add `--agent all` to install for every agent. Or copy the skill folder (the one holding SKILL.md) into the directory your agent reads:

| Agent | This project | Every project |
|---|---|---|
| Claude Code | `.claude/skills/` | `~/.claude/skills/` |
| Cursor | `.agents/skills/ (or .cursor/skills/)` | `~/.cursor/skills/` |
| Codex | `.agents/skills/` | `~/.agents/skills/` |
| Gemini CLI | `.agents/skills/ (or .gemini/skills/)` | `~/.gemini/skills/` |

Or with the open skills CLI, which reads this site's agent-skills discovery index:

```bash
npx skills add https://proskills.dev --skill analytics-sql
```

## patterns.md

````markdown
# Analytics pattern library

Read the dialect notes for the database in profile.md, then the pattern you need. Tables used: `events(user_id, name, occurred_at)`, `users(id, created_at)`, `orders(id, user_id, total, created_at)`. Contents: Dialect notes, Funnel, Cohort retention, DAU/WAU/MAU, Sessionisation, Dedupe latest row, Percentiles, Date spine, Running total and lag.

## Dialect notes

| Need | Postgres | BigQuery | Snowflake |
|---|---|---|---|
| Truncate to week | `date_trunc('week', ts)` (Monday) | `TIMESTAMP_TRUNC(ts, ISOWEEK)` or `DATE_TRUNC(d, WEEK(MONDAY))` | `DATE_TRUNC('week', ts)` (depends on `WEEK_START`, default Monday) |
| Convert time zone | `ts AT TIME ZONE 'America/New_York'` | `DATETIME(ts, 'America/New_York')` | `CONVERT_TIMEZONE('America/New_York', ts)` |
| Date difference | `d2 - d1` (integer days) | `DATE_DIFF(d2, d1, DAY)` | `DATEDIFF('day', d1, d2)` |
| Filter on window result | subquery or CTE | `QUALIFY` | `QUALIFY` |
| Exact percentile | `percentile_cont(0.95) WITHIN GROUP (ORDER BY x)` | `APPROX_QUANTILES(x, 100)[OFFSET(95)]` or `PERCENTILE_CONT(x, 0.95) OVER ()` | `PERCENTILE_CONT(0.95) WITHIN GROUP (ORDER BY x)` |
| Generate dates | `generate_series(d1, d2, interval '1 day')` | `GENERATE_DATE_ARRAY(d1, d2)` with `UNNEST` | `TABLE(GENERATOR(ROWCOUNT => n))` plus `DATEADD` |
| Approx distinct | `COUNT(DISTINCT x)` (exact) | `APPROX_COUNT_DISTINCT(x)` | `APPROX_COUNT_DISTINCT(x)` |
| Cost lever | indexes, `EXPLAIN (ANALYZE, BUFFERS)` | partition filter on the partition column, bytes billed | clustering, warehouse size, query profile |

Time zone rule for all three: store UTC, convert once in the first CTE, group by the converted date, state the zone in the answer. Half-open ranges everywhere: `>= start AND < end`.

## Funnel

Strict ordered funnel: a user counts at step N only if they did step N after step N-1.

```sql
WITH step1 AS (   -- grain: one row per user, first signup_view time
  SELECT user_id, MIN(occurred_at) AS t1 FROM events WHERE name = 'signup_view' GROUP BY user_id
),
step2 AS (        -- grain: one row per user, first signup_submit after t1
  SELECT s.user_id, MIN(e.occurred_at) AS t2
  FROM step1 s JOIN events e ON e.user_id = s.user_id AND e.name = 'signup_submit' AND e.occurred_at >= s.t1
  GROUP BY s.user_id
),
step3 AS (        -- grain: one row per user, first purchase after t2
  SELECT s.user_id, MIN(e.occurred_at) AS t3
  FROM step2 s JOIN events e ON e.user_id = s.user_id AND e.name = 'purchase' AND e.occurred_at >= s.t2
  GROUP BY s.user_id
)
SELECT (SELECT COUNT(*) FROM step1) AS viewed,
       (SELECT COUNT(*) FROM step2) AS submitted,
       (SELECT COUNT(*) FROM step3) AS purchased;
```

Add a conversion window by changing the join to `e.occurred_at < s.t1 + interval '7 days'` (Postgres), `TIMESTAMP_ADD(s.t1, INTERVAL 7 DAY)` (BigQuery), `DATEADD('day', 7, s.t1)` (Snowflake). Step rates divide by the previous step, overall rate by step 1. Check: counts must be non-increasing.

## Cohort retention

```sql
WITH cohorts AS (   -- grain: one row per user, cohort = signup week
  SELECT id AS user_id, date_trunc('week', created_at) AS cohort_week FROM users
),
activity AS (       -- grain: one row per (user, active week)
  SELECT DISTINCT user_id, date_trunc('week', occurred_at) AS active_week FROM events
),
joined AS (         -- grain: one row per (user, active week), weeks_since computed
  SELECT c.cohort_week, c.user_id, (a.active_week::date - c.cohort_week::date) / 7 AS weeks_since
  FROM cohorts c JOIN activity a ON a.user_id = c.user_id AND a.active_week >= c.cohort_week
),
sizes AS (SELECT cohort_week, COUNT(*) AS cohort_size FROM cohorts GROUP BY 1)  -- grain: one row per cohort
SELECT j.cohort_week, j.weeks_since, COUNT(DISTINCT j.user_id) AS retained,
       ROUND(COUNT(DISTINCT j.user_id)::numeric / s.cohort_size, 3) AS retention
FROM joined j JOIN sizes s USING (cohort_week)
GROUP BY j.cohort_week, j.weeks_since, s.cohort_size
ORDER BY 1, 2;
```

Week 0 must be near 100% (it is the signup week). Cells for weeks that have not happened yet must be absent, not 0: filter `cohort_week + weeks_since * 7 < current week`.

## DAU / WAU / MAU

```sql
-- grain: one row per day; WAU/MAU use trailing windows over distinct users, not sums of DAU
WITH days AS (SELECT DISTINCT occurred_at::date AS d, user_id FROM events)
SELECT d1.d,
       COUNT(DISTINCT d1.user_id) AS dau,
       (SELECT COUNT(DISTINCT user_id) FROM days w WHERE w.d >  d1.d - 7  AND w.d <= d1.d) AS wau,
       (SELECT COUNT(DISTINCT user_id) FROM days m WHERE m.d >  d1.d - 30 AND m.d <= d1.d) AS mau
FROM days d1 GROUP BY d1.d ORDER BY d1.d;
```

Never sum DAU to get WAU (double counts). On 100M+ rows, precompute `days` into a daily table and use `APPROX_COUNT_DISTINCT` on BigQuery and Snowflake. Stickiness is `dau / mau`.

## Sessionisation

New session when the gap to the previous event exceeds 30 minutes.

```sql
WITH ordered AS (   -- grain: one row per event, with previous event time
  SELECT user_id, occurred_at,
         LAG(occurred_at) OVER (PARTITION BY user_id ORDER BY occurred_at) AS prev_at
  FROM events
),
flagged AS (        -- grain: one row per event, 1 where a session starts
  SELECT *, CASE WHEN prev_at IS NULL OR occurred_at - prev_at > interval '30 minutes' THEN 1 ELSE 0 END AS is_start
  FROM ordered
)
SELECT user_id, occurred_at,
       SUM(is_start) OVER (PARTITION BY user_id ORDER BY occurred_at ROWS UNBOUNDED PRECEDING) AS session_number
FROM flagged;
```

BigQuery: `TIMESTAMP_DIFF(occurred_at, prev_at, MINUTE) > 30`. Snowflake: `DATEDIFF('minute', prev_at, occurred_at) > 30`. Ties on `occurred_at` need a second `ORDER BY` column (event id) or sessions flicker between runs.

## Dedupe: latest row per key

```sql
-- Postgres
SELECT * FROM (
  SELECT t.*, ROW_NUMBER() OVER (PARTITION BY id ORDER BY updated_at DESC, ingested_at DESC) AS rn FROM source t
) x WHERE rn = 1;
-- BigQuery and Snowflake
SELECT * FROM source
QUALIFY ROW_NUMBER() OVER (PARTITION BY id ORDER BY updated_at DESC, ingested_at DESC) = 1;
```

Always add a tie-breaker. Postgres alternative: `SELECT DISTINCT ON (id) * FROM source ORDER BY id, updated_at DESC`.

## Percentiles

Use the dialect row in the notes table. Report p50, p90, p99 together; a mean of a skewed metric (latency, order value) hides the tail. Percentiles cannot be averaged across groups: compute from raw rows or from histogram buckets. Filter NULLs explicitly; they are ignored, which shrinks the sample silently.

## Date spine

```sql
-- Postgres: every day shows, zero when empty
WITH spine AS (SELECT d::date AS d FROM generate_series('2025-01-01'::date, '2025-01-31'::date, interval '1 day') d),
daily AS (SELECT created_at::date AS d, COUNT(*) AS n FROM orders GROUP BY 1)
SELECT s.d, COALESCE(x.n, 0) AS orders FROM spine s LEFT JOIN daily x ON x.d = s.d ORDER BY s.d;
```

BigQuery: `FROM UNNEST(GENERATE_DATE_ARRAY('2025-01-01', '2025-01-31')) AS d`. Snowflake: `SELECT DATEADD('day', SEQ4(), '2025-01-01'::date) AS d FROM TABLE(GENERATOR(ROWCOUNT => 31))`.

## Running total and lag

```sql
SELECT d, orders,
       SUM(orders) OVER (ORDER BY d ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_orders,
       orders - LAG(orders) OVER (ORDER BY d) AS change_vs_prior_day,
       RANK() OVER (ORDER BY orders DESC) AS busiest_rank
FROM daily_orders;
```

Write the frame explicitly (`ROWS`, not the default `RANGE`, which treats ties as one row). `LAG` returns NULL on the first row; leave it NULL rather than inventing 0.
````

## SKILL.md

````markdown
---
name: analytics-sql
description: "Use when the user says 'write a query for', 'weekly active users', 'retention by cohort', 'funnel conversion', 'why do these numbers not match', 'fix this slow report query', 'running total by month', or wants a readable analytics SQL query. Produces a CTE-per-step query with the grain stated per CTE, join fan-out checks, date spines, time zone and NULL handling, a note on how to read the result and the sanity checks that were run. Reads profile.md for database, ORM, data size and conventions; pattern library per dialect in patterns.md."
---

# Analytics SQL

Write analytics queries that a colleague can read top to bottom and that give the same number twice. Most wrong dashboards come from three causes: a join that multiplied rows, a date boundary that leaked a day, or a NULL that silently dropped a group. This skill writes the query so each of those is visible and checked.

## Before you start

Read `profile.md` in this folder:

| profile.md line | Use |
|---|---|
| **Database** | Picks the dialect for date functions, `QUALIFY`, `DATE_TRUNC`, percentile syntax. Section of the same name in `patterns.md`. |
| **ORM** | If an ORM is named, write the query as raw SQL for the reporting path and show where it plugs in (view, raw query, dbt model). "none, raw SQL" means deliver plain SQL. |
| **Data size** | Under 1M rows: clarity first. 1M-100M: filter early on the partition or date column, avoid `SELECT *`. 100M+: partition pruning, pre-aggregated daily tables, approximate distinct counts where the user accepts them. |
| **Conventions** | Naming (snake_case, plural tables, `_at` timestamps, `_id` keys) and style rules. Follow them over your defaults. |

If a line says "not set", ask once, write it into profile.md, continue. Open `patterns.md` and read the section for the database and the pattern you need.

## Workflow

1. **Restate the question as a metric.** Name the numerator, the denominator, the grain of the answer (per user per week?), the time window and the time zone. If two readings are plausible, state both and ask which one.
2. **Find the tables and keys.** Read the schema or ask for it. Write down each table's grain ("one row per order line") and its unique key. Never guess a key; run a uniqueness check (below).
3. **Build in CTEs, one step each.** Every CTE starts with a comment line `-- grain: one row per <thing>`. Order: filter source, derive, join, aggregate, final select. No subquery nested deeper than one level.
4. **Join with intent.** Name the key on both sides, state the expected cardinality (1:1, 1:many), and aggregate the "many" side to the grain of the "one" side before joining.
5. **Handle time deliberately.** Convert to the reporting time zone once, in the first CTE. Use half-open ranges `>= start AND < end`. Build a date spine when empty days must show as 0.
6. **Run the sanity checks** (below) if you have a database connection. If you cannot run anything, say so and list the checks for the user to run. Never claim a check passed that you did not run.
7. **Deliver** in the Output format.

## Decision table

| Situation | Do this | Not this |
|---|---|---|
| Count users after joining orders | `COUNT(DISTINCT user_id)`, or aggregate orders to one row per user first | `COUNT(*)` after a 1:many join |
| Date range for "March" | `>= '2025-03-01' AND < '2025-04-01'` | `BETWEEN ... AND '2025-03-31'` (drops 31 March after midnight) |
| Group with no activity should show 0 | Date spine `LEFT JOIN` facts, `COALESCE(n, 0)` | Inner join that drops the empty day |
| Average of a nullable column | State that `AVG` ignores NULL; use `COALESCE` only if NULL truly means 0 | Silent `AVG` over a mostly-NULL column |
| Latest row per key | `ROW_NUMBER() ... = 1` (or `QUALIFY`) with a tie-breaker in `ORDER BY` | `MAX(updated_at)` self-join that returns ties twice |
| Ratio | `numerator / NULLIF(denominator, 0)` | Bare division |
| Anti-join | `NOT EXISTS`, or `LEFT JOIN ... WHERE r.key IS NULL` | `NOT IN (subquery)`; one NULL in the subquery returns nothing |

## Worked example: weekly active users by plan

Question: "Weekly active users by plan for the last 8 complete weeks, UTC, Postgres."

```sql
-- grain of the whole query: one row per (week, plan)
WITH params AS (
  -- grain: one row. Last 8 complete weeks (Monday start), half-open [start_ts, end_ts)
  SELECT date_trunc('week', now() AT TIME ZONE 'UTC') - interval '8 weeks' AS start_ts,
         date_trunc('week', now() AT TIME ZONE 'UTC')                       AS end_ts
),
events_in_range AS (
  -- grain: one row per event. Source: events(user_id, occurred_at timestamptz)
  SELECT e.user_id,
         date_trunc('week', e.occurred_at AT TIME ZONE 'UTC') AS week_start
  FROM events e, params p
  WHERE (e.occurred_at AT TIME ZONE 'UTC') >= p.start_ts
    AND (e.occurred_at AT TIME ZONE 'UTC') <  p.end_ts
    AND e.user_id IS NOT NULL
),
active_users AS (
  -- grain: one row per (week_start, user_id). Collapses many events to one user-week.
  SELECT DISTINCT week_start, user_id FROM events_in_range
),
plans AS (
  -- grain: one row per user. users.id is the primary key (check 1), so the join cannot fan out.
  SELECT id AS user_id, COALESCE(plan, 'unknown') AS plan FROM users
),
joined AS (
  -- grain: one row per (week_start, user_id), same as active_users
  SELECT a.week_start, a.user_id, p.plan
  FROM active_users a
  LEFT JOIN plans p ON p.user_id = a.user_id
)
SELECT week_start::date AS week, COALESCE(plan, 'unknown') AS plan, COUNT(*) AS weekly_active_users
FROM joined
GROUP BY 1, 2
ORDER BY 1, 2;
```

Sanity checks for this query (checks 2 and 3 read the CTEs, so run them after the same `WITH` block in place of the final `SELECT`):

```sql
-- 1. Key is unique (expect 0 rows)
SELECT id FROM users GROUP BY id HAVING COUNT(*) > 1;
-- 2. Join did not fan out (expect equal numbers)
SELECT (SELECT COUNT(*) FROM active_users) AS before_join,
       (SELECT COUNT(*) FROM joined)       AS after_join;
-- 3. Totals tie out: per-week distinct users must equal the sum of plan rows for that week
SELECT week_start, COUNT(DISTINCT user_id) FROM events_in_range GROUP BY 1;
```

How to read it: each row is the number of distinct users with at least one event in that UTC week. Plans sum to the week total because every user maps to exactly one plan. Users missing from `users` land in `unknown`; a large `unknown` row means events reference deleted users.

## Rules

- One grain per CTE, stated in a comment. If you cannot state it, the CTE does two jobs: split it.
- Count rows before and after every join that is not provably 1:1. A changed count is a blocker.
- Select named columns. `SELECT *` only inside a CTE that is a plain filter.
- Qualify every column in a join with its table alias.
- The time zone and the week start day (Monday or Sunday) are stated in the answer, never implied.
- Ask before running anything heavy against production. Add `LIMIT` and a date filter, or use a replica. On BigQuery or Snowflake, check bytes scanned or warehouse size first.
- Read-only: never write data or run DDL as part of an analysis unless the user asks.
- If a result looks surprising, say what you checked before saying it is real.

## Output

````markdown
## Query: <metric name>
**Question as understood:** <numerator / denominator / grain / window / time zone>
**Dialect:** <database>

```sql
<the query, every CTE with a grain comment>
```

### How to read the result
<columns, units, what one row means, what a zero or NULL means, known caveats>

### Sanity checks
| Check | Query or method | Result |
|---|---|---|
| Key uniqueness | ... | passed / not run |
| Join fan-out (rows before and after) | ... | 1,204 -> 1,204 |
| Totals tie out | ... | ... |

### Assumptions to confirm
<anything that would change the number>
````
````

## Changelog

- v1.0.0 (2026-10-16): First versioned release: Readable analytics queries you can trust. Scanned 100/100 before release.

## Related skills

- [Schema Designer](https://proskills.dev/skills/schema-designer): Tables, keys and constraints from your domain. ($9)
- [SQL Reviewer](https://proskills.dev/skills/sql-reviewer): Catches the NULL, fan-out and lock bugs. ($9)
- [Query Optimizer](https://proskills.dev/skills/query-optimizer): EXPLAIN-driven tuning with before and after timings. ($12)
- [Migration Planner](https://proskills.dev/skills/migration-planner): Zero-downtime schema changes, step by step. ($12)
- [Pipeline Debugger](https://proskills.dev/skills/data-pipeline-debugger): Finds the first bad table and fixes it at source. ($9)
