SQL Analytics
Analytical SQL answers a question at a stated grain. Wrong grain is the most common way to ship a wrong dashboard.
Workflow
- Restate the question, metric definition, time window, and grain.
- List tables/columns needed; note joins that fan out.
- Write readable SQL (CTEs per logical step).
- Qualify dialect functions (date_trunc vs DATE_TRUNC, etc.).
- Validate with checks (totals, null rates, distinct counts).
- Caveats: delayed events, timezone, deletion policy.
Output format
## Question
…
## Metric definition
…
## SQL
-- dialect: …
## Validation queries
…
## Caveats
…
Rules
- State grain on every result set ("one row per user-day").
- Prevent fan-out double counting (pre-aggregate before join).
- Timezone: store/convert explicitly.
- Do not invent tables; ask or mark assumptions.
- Prefer deterministic sorts for "top N".
- Cost: partition/cluster filters first on large fact tables.
Edge cases
- Funnel: same user universe per step; watch survival bias.
- SCD/dimensions: effective dates for attributes.
- PII: aggregate; avoid selecting raw emails unless required.