본문으로 건너뛰기
cccskills
무료GitHub에 공개

codexkit-sql-query-builder

Build production-ready analytical SQL queries using CTEs, window functions, aggregations, and data transformations. Translates business questions into well-documented, performant queries. Use when writing reporting queries, building data pipelines, or answering ad-hoc business questions with SQL.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

연동 도구PostgreSQL
설치 방법 보기

포함된 파일(6)

  • SKILL.md6.0 KB
  • agents/openai.yaml168 B
  • examples/common-mistakes.md842 B
  • examples/good-output.md1.2 KB
  • scripts/query-validator.sql3.6 KB
  • verification/checklist.md1.4 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

SQL Query Builder

When to Use

  • When a business question needs to be answered with data
  • When building reporting queries or data pipeline transformations
  • When optimizing slow queries or refactoring complex SQL
  • When translating stakeholder requirements into analytical SQL

Procedure

Step 1 — Clarify the Question

Translate the business question into a precise data question:

  • Business: "How are our sales trending?"
  • Data: "Monthly revenue by product category for the last 12 months, with month-over-month growth rate"

Document:

  • Expected output columns and format
  • Filters and date ranges
  • Granularity (daily, weekly, monthly)
  • Sort order

Step 2 — Identify Tables & Joins

Map the data model:

TableRoleKey ColumnsJoin
ordersFactorder_id, customer_id, order_date, totalPrimary
productsDimensionproduct_id, category, nameorders.product_id = products.id
customersDimensioncustomer_id, region, segmentorders.customer_id = customers.id

Join type selection:

  • INNER when both sides must exist
  • LEFT when the left side may have no match (preserve all orders even without customer data)
  • Never use RIGHT JOIN — rewrite as LEFT JOIN for clarity

Step 3 — Build CTE Pipeline

Structure complex queries as a pipeline of CTEs:

WITH
-- Step 1: Filter and clean base data
base AS (
    SELECT ...
    FROM orders
    WHERE order_date >= DATE_TRUNC('month', CURRENT_DATE - INTERVAL '12 months')
),

-- Step 2: Aggregate to desired granularity
monthly AS (
    SELECT
        DATE_TRUNC('month', order_date) AS month,
        category,
        SUM(total) AS revenue,
        COUNT(DISTINCT customer_id) AS unique_customers
    FROM base
    JOIN products USING (product_id)
    GROUP BY 1, 2
),

-- Step 3: Add calculations (window functions)
with_growth AS (
    SELECT *,
        LAG(revenue) OVER (PARTITION BY category ORDER BY month) AS prev_revenue,
        ROUND(100.0 * (revenue - LAG(revenue) OVER (PARTITION BY category ORDER BY month))
              / NULLIF(LAG(revenue) OVER (PARTITION BY category ORDER BY month), 0), 1) AS mom_growth_pct
    FROM monthly
)

-- Final output
SELECT month, category, revenue, unique_customers, mom_growth_pct
FROM with_growth
ORDER BY category, month;

Step 4 — Common Patterns Reference

PatternWhen to UseSQL
Running totalCumulative metricsSUM(x) OVER (ORDER BY date ROWS UNBOUNDED PRECEDING)
Rank within groupTop N per categoryROW_NUMBER() OVER (PARTITION BY cat ORDER BY val DESC)
Period comparisonYoY, MoMLAG(val, 12) OVER (ORDER BY month)
DeduplicationRemove exact dupesROW_NUMBER() OVER (PARTITION BY key ORDER BY updated DESC)
Cohort analysisRetention / engagementFirst-action date as cohort, then activity by period
PivotRows to columnsCASE WHEN + SUM or database-specific PIVOT

Step 5 — Performance Notes

Add comments for production queries:

  • Estimated row counts at each CTE stage
  • Index usage hints
  • Known limitations or edge cases
  • Data freshness assumptions

Inputs

InputRequiredFormat
Business questionYesPlain language
Table schemaYesTable names, columns, types
Database dialectRecommendedPostgreSQL / MySQL / BigQuery / Snowflake
Sample dataRecommendedTo validate output
Performance requirementsOptionalMax execution time

Output

## Query — [Business Question]

### Question
"What is the monthly revenue by category for the last 12 months with growth rates?"

### Query
[SQL with CTEs, comments, and formatting]

### Output Schema

| Column | Type | Description |
|--------|------|-------------|
| month | DATE | First day of month |
| category | VARCHAR | Product category |
| revenue | DECIMAL | Total revenue |
| unique_customers | INT | Distinct customers |
| mom_growth_pct | DECIMAL | Month-over-month growth % |

### Performance Notes
- Base table ~2M rows, filtered to ~200K
- Index on orders(order_date) recommended
- Runs in ~3s on PostgreSQL 15

Definition of Done

  • Business question clearly translated to data question
  • Tables and joins documented
  • Query uses CTE pipeline (no nested subqueries)
  • Window functions used where appropriate
  • Output columns described
  • Performance notes included

Quality Criteria

  • Data sources and assumptions are explicitly stated
  • Calculations are reproducible from provided inputs
  • Visualizations or tables have clear labels, units, and time ranges
  • Caveats and confidence levels are documented for estimates

Verification (4C)

CheckQuestion
CorrectnessAre formulas, aggregations, and statistical methods applied correctly?
CompletenessDoes the analysis cover all requested metrics and time ranges?
Context-fitAre the chosen metrics relevant to the business question being answered?
ConsequenceIf this data were used for a decision today, what blind spots remain?

Edge Cases

  • Missing or incomplete data — Document gaps and their potential impact on conclusions. Provide ranges instead of point estimates.
  • Outliers skewing results — Report with and without outliers. Document the decision to include or exclude.
  • Changing data definitions mid-period — Split analysis at the change boundary and note the schema difference.

Changelog

  • v1.1.0 — Added Tier 2 verification checklist and examples for query safety.
  • v1.0.0 — Initial release

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

Design rigorous A/B test plans with hypothesis, sample size calculation, Minimum Detectable Effect (MDE), randomization strategy, and decision rules. Includes guardrail metrics and rollout playbook. Use when planning product experiments, conversion optimization, or data-driven feature decisions.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

hoavdc/CodexKit252026년 10월 11일 업데이트

Review REST and GraphQL API designs for consistency, usability, and best practices. Covers naming conventions, versioning strategy, error format, pagination, authentication patterns, and breaking change detection. Use when reviewing API specs, designing new APIs, or auditing existing endpoints.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

hoavdc/CodexKit252026년 10월 11일 업데이트

Write Architecture Decision Records (ADRs) following the Michael Nygard format. Captures context, options considered, decision rationale, and consequences. Use when making technology choices, framework selections, or any architectural decision that future developers need to understand.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

hoavdc/CodexKit252026년 10월 11일 업데이트

Assess organizational readiness for financial audits (internal or external). Map assertions to account balances, check evidence completeness, score readiness using a Red/Amber/Green framework, and generate a remediation timeline. Aligned with SOX, IFRS, and GAAP audit standards. Use before scheduled audits or when preparing for first-time compliance.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

hoavdc/CodexKit252026년 10월 11일 업데이트

Design safe recurring Codex automations with clear prompts, outputs, schedules, and gating rules.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

hoavdc/CodexKit252026년 10월 11일 업데이트

Refine Product Backlog Items to meet INVEST criteria. Write User Stories with Acceptance Criteria in Given/When/Then format, estimate with Story Points, and flag dependencies. Use before sprint planning when backlog items need grooming. Do not use to prioritize the backlog — that is the Product Owner's decision.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

hoavdc/CodexKit252026년 10월 11일 업데이트

hoavdc의 스킬 모두 보기

이 스킬의 문제 신고