Write SQL and analytics queries with AI

Updated 2026-10-11 15 分钟 Difficulty ★☆☆☆☆Author Skills 编辑部

Skills used in this guide (3)

AI SQL's scare is "runs but wrong口径" — looks right, aggregation dimension wrong. The point: give schema and clear口径 (by day / by user, dedup?, exclude refunds), have it explain then write, not just "count sales".

Who this is for / not for

For:

  • Can't write complex SQL but need analysis
  • Have schema, want AI to generate query
  • Want AI help with create/alter (migrations)

Not for:

  • Prod DB, AI runs dangerous stmt directly (review first)
  • No口径 then blame result (you set口径)
  • Realtime millisecond (that's index/architecture)

Before you start

  1. Schema: fields & types of relevant tables.
  2. 口径: dimension, dedup?, filters.
  3. (Optional) sample: align expectation.

Steps

1. Install the skill

mysql-patterns is a MySQL skill. Copy its folder into your client's skills directory (same as any Agent Skill):

ClientDirectory
Claude Code~/.claude/skills/
Codex~/.codex/skills/
Cursor~/.cursor/skills/
Trae~/.trae/skills/
CodeBuddy~/.codebuddy/skills/
Tongyi Lingma~/.lingma/skills/

2. Schema, then口径

text
From orders(user_id, amount, status, created_at) and order_items,
write SQL for "paid users last 30d (distinct) + total GMV (status='paid', exclude refund)".
State aggregation口径 in one line, then statement, annotate each field.

3. PG use postgres-patterns

PostgreSQL has specifics (ILIKE, window fns); postgres-patterns avoids pitfalls.

4. Create/alter with database-migrations

Add/alter table → AI migration with rollback:

text
Add last_login_at to users, write migration SQL with rollback, comment the impact.

Pitfalls

PitSymptomFix
Wrong口径MismatchState口径 then write
No dedupUsers inflatedExplicit count(distinct)
Prod directDelete/lockReview then run, confirm danger
PG/MySQL mixSyntax errSpecify engine, use patterns
No rollbackHard recoverMigration with rollback

FAQ

No SQL, analyze?

Yes — give schema &口径; you verify result.

Define口径?

Dimension (day/user), dedup?, filters; state then run.

Prod direct?

No — review stmt, manual confirm for danger.

PG/MySQL same?

Not fully; specify engine, use patterns.

Migration rollback?

Yes — ask AI for rollback with migration.

Related guides

Continue across these scenes:

相关源码

一句话结论

结论:AI 写 SQL 先给表结构和口径再出语句,生产库先审再跑、迁移带回滚。

References

Related Scenes