
text-to-sql
Convert natural language queries to SQL. Use for database queries, data analysis, and reporting.
- Installs
- 156
- Last 24h
- —
- Trending rank
- —
- Security
- Not audited
Install
Works with every agent the skills CLI supports.
npx skills add https://github.com/oimiragieo/agent-studio --skill text-to-sql- 01
Install
Run the command in your project. The CLI asks which agents to install for.
- 02
Describe the task
Ask your agent for something this skill covers. It loads text-to-sql automatically when relevant.
- 03
Review the result
The agent follows the SKILL.md steps, scripts and references bundled with the skill.
SKILL.md
The instructions your agent reads when the skill is triggered.
Mode: Cognitive/Prompt-Driven — No standalone utility script; use via agent context.
Text-to-SQL Skill
Identity
Text-to-SQL - Converts natural language queries to SQL using database schema context and query patterns.
Capabilities
- Query Generation: Convert natural language to SQL
- Schema Awareness: Uses database schema for accurate queries
- Query Optimization: Generates optimized SQL queries
- Parameterized Queries: Creates safe, parameterized queries
Usage
Basic SQL Generation
When to Use:
- Database queries from natural language
- Data analysis requests
- Reporting queries
- Ad-hoc database queries
How to Invoke:
"Generate SQL to find all users who signed up in the last month"
"Create a query to calculate total revenue by product"
"Write SQL to find duplicate records"
What It Does:
- Analyzes natural language query
- References database schema
- Generates SQL query
- Validates query syntax
- Returns parameterized query
Advanced Features
Schema Integration:
- Loads database schema
- Understands table relationships
- Uses column types and constraints
- Handles joins and aggregations
Query Optimization:
- Generates efficient queries
- Uses appropriate indexes
- Optimizes joins
- Minimizes data transfer
Safety:
- Parameterized queries (prevents SQL injection)
- Validates query syntax
- Tests on sample data
- Error handling
Best Practices
- Schema Context: Provide complete database schema
- Query Validation: Validate SQL before execution
- Parameterization: Always use parameterized queries
- Testing: Test queries on sample data
- Optimization: Review query performance
Integration
With Database Architect
Text-to-SQL uses schema from database-architect:
- Table definitions
- Relationships
- Constraints
- Indexes
With Developer
Text-to-SQL generates queries for developers:
- Query templates
- Parameterized queries
- Query optimization
- Error handling
Examples
Example 1: Simple Query
User: "Find all users who signed up in the last month"
Text-to-SQL:
1. Analyzes query
2. References users table schema
3. Generates SQL:
SELECT * FROM users
WHERE created_at >= DATE_SUB(NOW(), INTERVAL 1 MONTH)
4. Returns parameterized query
Example 2: Complex Query
User: "Calculate total revenue by product for Q4"
Text-to-SQL:
1. Analyzes query
2. References orders and products tables
3. Generates SQL:
SELECT p.name, SUM(o.total) as revenue
FROM orders o
JOIN products p ON o.product_id = p.id
WHERE o.created_at >= '2024-10-01'
AND o.created_at < '2025-01-01'
GROUP BY p.id, p.name
4. Returns optimized query
Evaluation
Evaluation Framework
Based on Claude Cookbooks patterns, text-to-SQL evaluation includes:
Syntax Validation:
- SQL syntax correctness
- Schema compliance
- Query structure validation
Functional Testing:
- Query execution on test database
- Result correctness
- Performance validation
Promptfoo Integration:
- Multiple prompt variants (basic, few-shot, chain-of-thought, RAG)
- Temperature sweeps
- Model comparisons (Haiku vs Sonnet)
Evaluation Configuration:
Create a promptfoo config file for your evaluation setup (e.g., text_to_sql_config.yaml).
Running Evaluations
# Run text-to-SQL evaluation (create config first)
npx promptfoo@latest eval -c text_to_sql_config.yaml
Evaluation Metrics
- Syntax Accuracy: Percentage of queries with valid SQL syntax
- Functional Correctness: Percentage of queries returning correct results
- Schema Compliance: Percentage of queries using correct schema
- Performance: Query execution time and optimization
Best Practices from Cookbooks
1. Provide Schema Context
Always include complete database schema:
- Table definitions with column types
- Relationships and foreign keys
- Constraints and indexes
- Sample data patterns
2. Use Few-Shot Examples
Provide examples of similar queries:
- Simple queries
- Complex queries with joins
- Aggregation queries
- Subquery patterns
3. Chain-of-Thought for Complex Queries
For complex queries, use chain-of-thought reasoning:
- Break down query into steps
- Identify required tables
- Plan joins and aggregations
- Generate SQL step by step
4. RAG for Schema Understanding
Use RAG to retrieve relevant schema information:
- Find relevant tables for query
- Understand relationships
- Get column details
- Retrieve query patterns
Related Skills
- classifier: Classify database queries
- database-architect: Use for schema design
- developer: Generate query code
Related Documentation
- Classification Patterns - Classification guide
- Evaluation Guide - Comprehensive evaluation
- Claude Cookbooks - Text-to-SQL
Iron Laws
- ALWAYS validate all table and column names against the provided schema before generating SQL
- NEVER use string interpolation for query values — parameterized queries are mandatory without exception
- ALWAYS apply a
LIMITclause (default 100) to SELECT queries unless the user explicitly overrides it - NEVER execute DROP, DELETE, TRUNCATE, or UPDATE statements without explicit user confirmation
- ALWAYS explain the generated query logic in plain language so the user understands what will execute
Anti-Patterns
| Anti-Pattern | Why It Fails | Correct Approach |
|---|---|---|
| String interpolation for values | SQL injection vulnerability | Use parameterized queries with ? or $N placeholders |
| No LIMIT clause on SELECT | Returns all rows, risk of OOM and timeout | Default LIMIT 100, require explicit user override |
| Destructive SQL without confirmation | Irreversible data loss | Gate DROP/DELETE/TRUNCATE behind user confirmation |
| No schema validation | References non-existent tables or columns | Validate all identifiers against the provided schema |
| SELECT * without column list | Unpredictable results and performance waste | Always specify an explicit column list |
Memory Protocol (MANDATORY)
Before starting:
Read .claude/context/memory/learnings.md
After completing:
- New pattern ->
.claude/context/memory/learnings.md - Issue found ->
.claude/context/memory/issues.md - Decision made ->
.claude/context/memory/decisions.md
FAQ
What does the text-to-sql skill do?
Convert natural language queries to SQL. Use for database queries, data analysis, and reporting.
How do I install text-to-sql?
Run npx skills add https://github.com/oimiragieo/agent-studio --skill text-to-sql in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/text-to-sql/ (personal) or .claude/skills/text-to-sql/ (project).
Which AI agents can use text-to-sql?
Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.
Is text-to-sql safe to install?
No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.
Who maintains text-to-sql?
It is published by oimiragieo in oimiragieo/agent-studio. It has 156 recorded installs.
More from oimiragieo/agent-studio
pyqt6-ui-development-rules
oimiragieo/agent-studio
PyQt6 desktop GUI development rules -- signal/slot architecture, QSS theming, QThread concurrency, layout management, and cross-platform rendering. Enforces MVC separation and responsive UI patterns.
filesystem
oimiragieo/agent-studio
File system operations guidance - read, write, search, and manage files using Claude Code's built-in tools.
chrome-browser
oimiragieo/agent-studio
Open the skill to read its SKILL.md instructions.
slack-notifications
oimiragieo/agent-studio
Open the skill to read its SKILL.md instructions.
context-compressor
oimiragieo/agent-studio
Compress large context before reasoning to reduce token usage while preserving evidence. Use this whenever the user mentions huge files, long prompts, RAG payloads, prompt caching, expensive sessions, codebase context, chat history compaction, or wants the same answer quality with fewer tokens.
nodejs-expert
oimiragieo/agent-studio
Node.js backend expert including Express, NestJS, and async patterns
Popular data & databases skills
supabase-postgres-best-practices
supabase/agent-skills
Postgres best practices maintained by Supabase, for Postgres running anywhere. Load this skill BEFORE writing or changing anything that lives in a Postgres database: creating or altering tables and columns (including choosing column types), schema design, migrations and declarative schema files, RLS policies and the tests that verify them, indexes, triggers, database functions, queues and scheduled jobs (pgcron, pgmq), vector/semantic search (pgvector), and restoring dumps (pgrestore) or importing data. Also load it when diagnosing slow queries, high CPU, timeouts, EXPLAIN plans, connection exhaustion, locking, bloat, or rows visible to the wrong user or tenant. This is not just a performance guide — schema, migration, security, and SQL authoring tasks need these rules too, even for a one-column change or a single query.
prisma-client-api
prisma/skills
Prisma Client API reference covering model queries, filters, operators, and client methods. Use when writing database queries, using CRUD operations, filtering data, or configuring Prisma Client. Triggers on "prisma query", "findMany", "create", "update", "delete", "$transaction".
prisma-database-setup
prisma/skills
Deprecated compatibility name for prisma-orm-setup. Use only when a user or existing integration explicitly invokes prisma-database-setup; otherwise select prisma-orm-setup.
prisma-cli
prisma/skills
Prisma ORM 7 CLI reference for existing Prisma 7 applications or explicitly selected Prisma 7 workflows. Covers prisma init, generate, migrate, db, dev, studio, and mcp. For setup, connection repair, or Prisma 8, use prisma-orm-setup; not the Prisma Platform CLI.
prisma-postgres
prisma/skills
Deprecated compatibility name for prisma-postgres-setup. Use only when a user or existing integration explicitly invokes prisma-postgres; otherwise select prisma-postgres-setup.
prisma-driver-adapter-implementation
prisma/skills
Required reference for Prisma ORM 7 SQL driver adapter work. Use when implementing or modifying adapters, adding database drivers, or touching SqlDriverAdapter, Transaction, savepoint, result mapping, or DriverAdapterError behavior. Covers current transaction lifecycle, optional savepoint hooks, original database-error preservation, and verification.