---
name: sql-query-builder
description: "A correct SQL query for a plain-English question, with the join risks called out so row counts and totals are not silently inflated. Use when someone can describe a data question in plain English and needs a trustworthy SQL query against a known schema. Do not use for designing a schema or tuning a slow production query plan. Related topics: Data, Technical, Coding."
---

# SQL Query Builder

A correct SQL query for a plain-English question, with the join risks called out so row counts and totals are not silently inflated.

## When to use

Use this skill when someone can describe a data question in plain English and needs a trustworthy SQL query against a known schema. Do not use it for designing a schema or tuning a slow production query plan.

## Workflow

1. Ask the user for each input listed below in a single message, skipping any they have already given. Where options are listed, offer them, but accept other answers too.
2. Map the question to the tables and columns in the schema and note the grain of the result.
3. Write the query in the chosen dialect, formatted and commented where the logic is not obvious.
4. Check each join for fan-out against the keys and aggregate before joining where needed.
5. Describe the null handling and whether an index is justified at the stated row counts.
6. Provide a sanity-check query that compares the result to a known count or total.

## Inputs

- **Schema** (longer free text)
- **Question to answer** (longer free text)
- **Database** (choose one: PostgreSQL, MySQL, BigQuery, Snowflake, SQL Server, SQLite)
- **Rough table sizes** (free text, e.g. "Row counts since they change the approach")

## Output

The formatted query, a short join and null explanation, an index note, and a sanity-check query.

## Prompt template

Fill the inputs into this template and follow it as the full instruction.

### SQL Query

Write the query for the question below.

Schema: {{Schema}}

Question to answer: {{Question to answer}}

Database: {{Database}}

Rough table sizes: {{Rough table sizes}}

Give the query formatted for readability, in the dialect of the chosen database, with comments on anything non-obvious.

Then explain what each join does and where one could fan out and duplicate rows, since that error silently inflates every number downstream. Say how nulls are handled and whether the query needs an index at these row counts.

Finish with a quick sanity check I can run to confirm the result is right, such as a count comparison or a known total.

## Pitfalls

- Joining a one-to-many table before aggregating, which multiplies rows and inflates sums.
- Using dialect-specific functions from the wrong database.
- Filtering on a nullable column in a way that silently drops rows.
