Write, debug, review or optimize analytical SQL for SQL Server, PostgreSQL, MySQL or DuckDB. Use for joins, CTEs, window functions, running totals, rolling averages, ranking, top-N, cohort and retention queries, period-over-period comparisons, deduplication, gap detection, conditional aggregation, row multiplication (fan-out) after joins, wrong totals from SQL, reading execution plans and indexing, and speeding up a query without changing its results.
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Sql Analytics Expert?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/khoavd18-sql-analytics-expert)
---
name: sql-analytics-expert
description: Write, debug, review or optimize analytical SQL for SQL Server, PostgreSQL, MySQL or DuckDB. Use for joins, CTEs, window functions, running totals, rolling averages, ranking, top-N, cohort and retention queries, period-over-period comparisons, deduplication, gap detection, conditional aggregation, row multiplication (fan-out) after joins, wrong totals from SQL, reading execution plans and indexing, and speeding up a query without changing its results.
---
# SQL Analytics Expert
Correctness first, then performance. Every query states its output grain.
## Inputs
- SQL dialect and version. Ask or detect: `TOP`/`GETDATE()` means SQL Server, `::`/`ILIKE` means PostgreSQL, backticks mean MySQL.
- Table schemas, keys, approximate row counts, and the intended output grain.
## Procedure
1. **Dialect**: confirm it. Date functions, string concatenation, `LIMIT`/`TOP` and NULL ordering all differ.
2. **Schemas and keys**: check primary/unique keys. If none are declared, test candidate keys with `GROUP BY ... HAVING COUNT(*) > 1`.
3. **Grain**: write `-- grain: one row per ...` for each CTE and for the final result.
4. **Design**: aggregate *before* joining when the sides have different grain. Use CTEs named after what they contain.
5. **Fan-out check**: compare the row count and a summed measure before and after each join (see [sql-validation-and-performance.md](references/sql-validation-and-performance.md)).
6. **Filters and dates**: use half-open ranges (`>= start AND < next_start`). Avoid `BETWEEN` on timestamps, and avoid functions on indexed columns in `WHERE`. State the time zone.
7. **NULLs**: `NOT IN` with a NULL in the subquery returns nothing, so prefer `NOT EXISTS`. `COUNT(col)` skips NULLs. Use `COALESCE` only when the business rule says NULL means zero.
8. **Aggregation**: compute ratios as `SUM(num) / NULLIF(SUM(den), 0)`, never as `AVG(ratio)` unless the contract says so. Watch for integer division (SQL Server, PostgreSQL).
9. **Control totals**: reconcile the final total against an independent simpler query or the source system.
10. **Optimize** only after correctness is established. Compare the old and new results with an EXCEPT-both-ways check, and compare the plans.
Pattern library: [sql-patterns.md](references/sql-patterns.md).
## Rules
- Never add `DISTINCT` to hide duplicates from a join. Find the join that multiplies rows and fix the grain.
- `INNER JOIN` and `LEFT JOIN` are not interchangeable. Decide whether unmatched rows must survive, and count them.
- Any result that depends on row order (`ROW_NUMBER`, `TOP`, `LIMIT`, first/last value) needs a deterministic `ORDER BY` with a unique tie-breaker.
- Handle duplicate business keys explicitly: dedupe with a documented rule, or fail.
- Parameterize. Never build SQL by concatenating user input.
- Do not run `UPDATE`, `DELETE`, `TRUNCATE`, `DROP`, `ALTER` or `MERGE` against shared or production data without explicit authorization. Prefer `SELECT` previews and transactions.
- An optimization is accepted only when result equivalence is shown on representative data.
## Outputs
The query with grain comments, the validation queries used and their results (row counts, control totals), the dialect assumptions, and, for optimization, before/after timing and plan notes.
## Hand-offs
Metric semantics → **kpi-metrics-engineer**. Recurring loads → **data-pipeline-engineer**. Formal reconciliation and regression suites → **data-quality-auditor**.