/write-query - Write Optimized SQL
If you see unfamiliar placeholders or need to check which tools are connected, see CONNECTORS.md.
Write a SQL query from a natural language description, optimized for your specific SQL dialect and following best practices.
Usage
/write-query <description of what data you need>
Workflow
1. Understand the Request
Parse the user's description to identify:
- Output columns: What fields should the result include?
- Filters: What conditions limit the data (time ranges, segments, statuses)?
- Aggregations: Are there GROUP BY operations, counts, sums, averages?
- Joins: Does this require combining multiple tables?
- Ordering: How should results be sorted?
- Limits: Is there a top-N or sample requirement?
2. Determine SQL Dialect
If the user's SQL dialect is not already known, ask which they use:
- PostgreSQL (including Aurora, RDS, Supabase, Neon)
- Snowflake
- BigQuery (Google Cloud)
- Redshift (Amazon)
- Databricks SQL
- MySQL (including Aurora MySQL, PlanetScale)
- SQL Server (Microsoft)
- DuckDB
- SQLite
- Other (ask for specifics)
Remember the dialect for future queries in the same session.
3. Discover Schema (If Warehouse Connected)
If a data warehouse MCP server is connected:
- Search for relevant tables based on the user's description
- Inspect column names, types, and relationships
- Check for partitioning or clustering keys that affect performance
- Look for pre-built views or materialized views that might simplify the query
4. Write the Query
Follow these best practices:
Structure:
- Use CTEs (WITH clauses) for readability when queries have multiple logical steps
- One CTE per logical transformation or data source
- Name CTEs descriptively (e.g.,
daily_signups, active_users, revenue_by_product)
Performance:
- Never use
SELECT * in production queries -- specify only needed columns
- Filter early (push WHERE clauses as close to the base tables as possible)
- Use partition filters when available (especially date partitions)
- Prefer
EXISTS over IN for subqueries with large result sets
- Use appropriate JOIN types (don't use LEFT JOIN when INNER JOIN is correct)
- Avoid correlated subqueries when a JOIN or window function works
- Be mindful of exploding joins (many-to-many)
Readability:
- Add comments explaining the "why" for non-obvious logic
- Use consistent indentation and formatting
- Alias tables with meaningful short names (not just
a, b, c)
- Put each major clause on its own line
Dialect-specific optimizations:
- Apply dialect-specific syntax and functions (see
sql-queries skill for details)
- Use dialect-appropriate date functions, string functions, and window syntax
- Note any dialect-specific performance features (e.g., Snowflake clustering, BigQuery partitioning)
5. Present the Query
Provide:
- The complete query in a SQL code block with syntax highlighting
- Brief explanation of what each CTE or section does
- Performance notes if relevant (expected cost, partition usage, potential bottlenecks)
- Modification suggestions -- how to adjust for common variations (different time range, different granularity, additional filters)
6. Offer to Execute
If a data warehouse is connected, offer to run the query and analyze the results. If the user wants to run it themselves, the query is ready to copy-paste.
Examples
Simple aggregation:
/write-query Count of orders by status for the last 30 days
Complex analysis:
/write-query Cohort retention analysis -- group users by their signup month, then show what percentage are still active (had at least one event) at 1, 3, 6, and 12 months after signup
Performance-critical:
/write-query We have a 500M row events table partitioned by date. Find the top 100 users by event count in the last 7 days with their most recent event type.
Tips
- Mention your SQL dialect upfront to get the right syntax immediately
- If you know the table names, include them -- otherwise Claude will help you find them
- Specify if you need the query to be idempotent (safe to re-run) or one-time
- For recurring queries, mention if it should be parameterized for date ranges
1---2name: write-query3description: Write optimized SQL for your dialect with best practices. Use when translating a natural-language data need into SQL, building a multi-CTE query with joins and aggregations, optimizing a query against a large partitioned table, or getting dialect-specific syntax for Snowflake, BigQuery, Postgres, etc.4---56# /write-query - Write Optimized SQL78> If you see unfamiliar placeholders or need to check which tools are connected, see [CONNECTORS.md](../CONNECTORS-data.md).910Write a SQL query from a natural language description, optimized for your specific SQL dialect and following best practices.1112## Usage1314```15/write-query <description of what data you need>16```1718## Workflow1920### 1. Understand the Request2122Parse the user's description to identify:2324- **Output columns**: What fields should the result include?25- **Filters**: What conditions limit the data (time ranges, segments, statuses)?26- **Aggregations**: Are there GROUP BY operations, counts, sums, averages?27- **Joins**: Does this require combining multiple tables?28- **Ordering**: How should results be sorted?29- **Limits**: Is there a top-N or sample requirement?3031### 2. Determine SQL Dialect3233If the user's SQL dialect is not already known, ask which they use:3435- **PostgreSQL** (including Aurora, RDS, Supabase, Neon)36- **Snowflake**37- **BigQuery** (Google Cloud)38- **Redshift** (Amazon)39- **Databricks SQL**40- **MySQL** (including Aurora MySQL, PlanetScale)41- **SQL Server** (Microsoft)42- **DuckDB**43- **SQLite**44- **Other** (ask for specifics)4546Remember the dialect for future queries in the same session.4748### 3. Discover Schema (If Warehouse Connected)4950If a data warehouse MCP server is connected:51521. Search for relevant tables based on the user's description532. Inspect column names, types, and relationships543. Check for partitioning or clustering keys that affect performance554. Look for pre-built views or materialized views that might simplify the query5657### 4. Write the Query5859Follow these best practices:6061**Structure:**62- Use CTEs (WITH clauses) for readability when queries have multiple logical steps63- One CTE per logical transformation or data source64- Name CTEs descriptively (e.g., `daily_signups`, `active_users`, `revenue_by_product`)6566**Performance:**67- Never use `SELECT *` in production queries -- specify only needed columns68- Filter early (push WHERE clauses as close to the base tables as possible)69- Use partition filters when available (especially date partitions)70- Prefer `EXISTS` over `IN` for subqueries with large result sets71- Use appropriate JOIN types (don't use LEFT JOIN when INNER JOIN is correct)72- Avoid correlated subqueries when a JOIN or window function works73- Be mindful of exploding joins (many-to-many)7475**Readability:**76- Add comments explaining the "why" for non-obvious logic77- Use consistent indentation and formatting78- Alias tables with meaningful short names (not just `a`, `b`, `c`)79- Put each major clause on its own line8081**Dialect-specific optimizations:**82- Apply dialect-specific syntax and functions (see `sql-queries` skill for details)83- Use dialect-appropriate date functions, string functions, and window syntax84- Note any dialect-specific performance features (e.g., Snowflake clustering, BigQuery partitioning)8586### 5. Present the Query8788Provide:89901. **The complete query** in a SQL code block with syntax highlighting912. **Brief explanation** of what each CTE or section does923. **Performance notes** if relevant (expected cost, partition usage, potential bottlenecks)934. **Modification suggestions** -- how to adjust for common variations (different time range, different granularity, additional filters)9495### 6. Offer to Execute9697If a data warehouse is connected, offer to run the query and analyze the results. If the user wants to run it themselves, the query is ready to copy-paste.9899## Examples100101**Simple aggregation:**102```103/write-query Count of orders by status for the last 30 days104```105106**Complex analysis:**107```108/write-query Cohort retention analysis -- group users by their signup month, then show what percentage are still active (had at least one event) at 1, 3, 6, and 12 months after signup109```110111**Performance-critical:**112```113/write-query We have a 500M row events table partitioned by date. Find the top 100 users by event count in the last 7 days with their most recent event type.114```115116## Tips117118- Mention your SQL dialect upfront to get the right syntax immediately119- If you know the table names, include them -- otherwise Claude will help you find them120- Specify if you need the query to be idempotent (safe to re-run) or one-time121- For recurring queries, mention if it should be parameterized for date ranges