Database Query (Natural Language)
⚡ UNIQUE FEATURE: Query any database using natural language - automatically generates optimized SQL/NoSQL queries, explains query plans, suggests indexes, and visualizes results. Supports PostgreSQL, MySQL, MongoDB, SQLite, and more.
What This Skill Does
Transform natural language into optimized database queries:
- Natural language to SQL: "Show me users who signed up last month" →
SELECT * FROM users WHERE created_at >= NOW() - INTERVAL '1 month'
- Multi-database support: PostgreSQL, MySQL, MongoDB, SQLite, Redis
- Query optimization: Analyzes queries and suggests improvements
- Index suggestions: Recommends indexes for slow queries
- Visual results: Formats query results as tables, charts, JSON
- Query explanation: EXPLAIN ANALYZE with human-readable insights
- Safe mode: Read-only by default with confirmation for writes
- Schema discovery: Auto-learns database structure
Why This Is Unique
First Claude Code skill that:
- Understands intent: Translates vague requests to precise queries
- Cross-database compatible: Same natural language works across SQL/NoSQL
- Performance-aware: Automatically optimizes and suggests indexes
- Safety-first: Prevents destructive operations without confirmation
- Learning mode: Improves by understanding your schema
Instructions
Phase 1: Database Connection & Discovery
Identify Database:
Ask user:
- Database type (PostgreSQL, MySQL, MongoDB, SQLite, etc.)
- Connection method (local, remote, Docker, MCP server)
- Connection string or credentials
Test Connection:
# PostgreSQL
psql -h localhost -U user -d database -c "SELECT version();"
# MySQL
mysql -h localhost -u user -p database -e "SELECT VERSION();"
# MongoDB
mongosh "mongodb://localhost:27017/database" --eval "db.version()"
# SQLite
sqlite3 database.db "SELECT sqlite_version();"
Discover Schema:
# PostgreSQL: Get all tables and columns
psql -d database -c "\dt"
psql -d database -c "\d+ table_name"
# MySQL: Show database structure
mysql database -e "SHOW TABLES;"
mysql database -e "DESCRIBE table_name;"
# MongoDB: List collections and sample documents
mongosh database --eval "db.getCollectionNames()"
mongosh database --eval "db.collection.findOne()"
Build Schema Cache:
- Store table/collection names
- Store column names and types
- Store relationships (foreign keys)
- Cache common queries
Phase 2: Natural Language to Query Translation
When user makes a request:
Parse Intent:
Analyze the request:
- Action: SELECT, INSERT, UPDATE, DELETE, aggregation
- Entities: Which tables/collections
- Conditions: WHERE clauses
- Aggregations: COUNT, SUM, AVG, GROUP BY
- Sorting: ORDER BY
- Limits: TOP N, pagination
Generate Query:
Example 1: "Show me all active users"
-- PostgreSQL/MySQL
SELECT * FROM users WHERE status = 'active';
Example 2: "Count orders by status for last 7 days"
SELECT status, COUNT(*) as count
FROM orders
WHERE created_at >= NOW() - INTERVAL '7 days'
GROUP BY status
ORDER BY count DESC;
Example 3: "Find top 10 customers by revenue"
SELECT
c.name,
c.email,
SUM(o.total) as revenue
FROM customers c
JOIN orders o ON c.id = o.customer_id
GROUP BY c.id, c.name, c.email
ORDER BY revenue DESC
LIMIT 10;
Example 4: MongoDB aggregation
db.orders.aggregate([
{ $match: { status: "completed" } },
{ $group: {
_id: "$customer_id",
total: { $sum: "$amount" }
}},
{ $sort: { total: -1 } },
{ $limit: 10 }
])
Validate Query:
- Check table/column names exist
- Verify data types match
- Ensure joins are valid
- Detect potentially dangerous operations
Phase 3: Query Optimization
Before execution:
Analyze Query Plan:
-- PostgreSQL
EXPLAIN ANALYZE
SELECT * FROM users WHERE email LIKE '%@example.com';
Suggest Optimizations:
If sequential scan detected:
- "This query is scanning all rows. Consider adding an index:"
- CREATE INDEX idx_users_email ON users(email);
If N+1 query pattern:
- "Use JOIN instead of multiple queries"
- Show optimized version
If missing WHERE clause:
- "This will return all rows. Add filters or LIMIT?"
Rewrite for Performance:
-- Before (slow)
SELECT * FROM users WHERE LOWER(email) = 'user@example.com';
-- After (fast - uses index)
SELECT * FROM users WHERE email = 'user@example.com';
Phase 4: Safe Execution
Determine Query Type:
- Read-only (SELECT): Execute immediately
- Write (INSERT, UPDATE, DELETE): Ask confirmation
- DDL (CREATE, DROP, ALTER): Require explicit confirmation
Confirmation for Writes:
⚠️ This query will modify data:
UPDATE users SET status = 'inactive'
WHERE last_login < '2024-01-01'
Estimated affected rows: 1,247
Proceed? [yes/no]
Transaction Support:
BEGIN;
-- Execute query
-- Show results
-- Ask: COMMIT or ROLLBACK?
Phase 5: Results Formatting
Table Format (default):
┌────┬─────────────┬──────────────────────┬──────────┐
│ id │ name │ email │ status │
├────┼─────────────┼──────────────────────┼──────────┤
│ 1 │ John Doe │ john@example.com │ active │
│ 2 │ Jane Smith │ jane@example.com │ active │
└────┴─────────────┴──────────────────────┴──────────┘
2 rows returned in 0.023s
Chart Format (for aggregations):
Orders by Status:
pending ████████████░░░░░░░░ 62
completed ████████████████████ 128
cancelled ████░░░░░░░░░░░░░░░░ 15
JSON Format (for APIs):
{
"query": "SELECT * FROM users LIMIT 2",
"execution_time": "0.023s",
"row_count": 2,
"results": [
{"id": 1, "name": "John Doe", ...},
{"id": 2, "name": "Jane Smith", ...}
]
}
Export Options:
- CSV file
- JSON file
- Markdown table
- Copy to clipboard
Examples
Example 1: Simple Query
User: "Show me recent users"
Skill:
- Interprets "recent" as last 7 days
- Generates query:
SELECT * FROM users
WHERE created_at >= NOW() - INTERVAL '7 days'
ORDER BY created_at DESC;
- Executes and displays results
- Suggests: "Want to filter by status or role?"
Example 2: Complex Aggregation
User: "Which products had the most revenue last quarter?"
Skill:
- Determines tables: products, orders, order_items
- Calculates "last quarter" date range
- Generates optimized query:
SELECT
p.id,
p.name,
SUM(oi.quantity * oi.price) as revenue,
COUNT(DISTINCT o.id) as order_count
FROM products p
JOIN order_items oi ON p.id = oi.product_id
JOIN orders o ON oi.order_id = o.id
WHERE o.created_at >= DATE_TRUNC('quarter', NOW() - INTERVAL '3 months')
AND o.created_at < DATE_TRUNC('quarter', NOW())
AND o.status = 'completed'
GROUP BY p.id, p.name
ORDER BY revenue DESC
LIMIT 10;
- Shows results with chart
- Offers to export
Example 3: Performance Investigation
User: "Why is this query slow?"
SELECT * FROM orders WHERE customer_name LIKE 'John%';
Skill:
- Runs EXPLAIN ANALYZE
- Detects: Sequential scan on 10M rows
- Suggests:
⚠️ Performance Issue Detected:
Problem: Full table scan (10,485,234 rows)
Solution: Add an index on customer_name
CREATE INDEX idx_orders_customer_name ON orders(customer_name);
Expected improvement: 10,485,234 rows → ~42 rows
Estimated speed-up: 10,000x faster
Would you like me to create this index?
Configuration
Create .database-query-config.yml:
databases:
- name: production
type: postgresql
host: localhost
port: 5432
database: myapp
user: readonly_user
ssl: true
read_only: true
- name: analytics
type: mongodb
uri: mongodb://localhost:27017/analytics
- name: cache
type: redis
host: localhost
port: 6379
defaults:
max_rows: 1000
timeout: 30s
explain_threshold: 1s # Auto-explain queries slower than 1s
auto_optimize: true
safety:
require_confirmation_for_writes: true
prevent_drop_table: true
max_affected_rows: 10000
Tool Requirements
- Bash: Execute database CLI commands
- Read: Read config files and schema cache
- Write: Save query results and reports
- Task: Launch optimization analyzer agent
Integration with MCP
Connect to MCP database servers:
# Using PostgreSQL MCP server
mcp_servers:
- name: postgres
command: postgres-mcp
args:
- --connection-string
- postgresql://user:pass@localhost/db
Advanced Features
1. Query History & Favorites
# Save favorite queries
claude db save "monthly_revenue" "SELECT..."
# Run saved query
claude db run monthly_revenue
2. Query Templates
-- Template: user_search
SELECT * FROM users
WHERE {{field}} = {{value}}
AND status = 'active';
3. Data Migration Helper
# Generate migration between databases
claude db migrate --from postgres://... --to mysql://...
4. Schema Diff
# Compare two databases
claude db diff production staging
Best Practices
- Start with schema: Let skill discover your database first
- Use read-only mode: For production databases
- Review before writes: Always check UPDATE/DELETE affects
- Monitor performance: Pay attention to optimization suggestions
- Save common queries: Build a library of frequently-used queries
- Use transactions: For multi-step operations
Limitations
- Maximum 10,000 rows displayed (configurable)
- Query timeout: 30 seconds (configurable)
- Write operations require confirmation
- Some database-specific features may not translate
- Complex stored procedures not supported
Security
- Never stores credentials in plain text
- Read-only mode by default
- SQL injection prevention
- Confirms destructive operations
- Audit logging available
Related Skills
Changelog
Version 1.0.0 (2025-01-13)
- Initial release
- PostgreSQL, MySQL, MongoDB, SQLite support
- Natural language query translation
- Query optimization and EXPLAIN
- Multiple output formats
- Safe mode with confirmations
Contributing
Help expand database support:
- Add new database types (CockroachDB, DynamoDB, Cassandra)
- Improve query optimization
- Add more visualization options
- Create query templates
License
Apache License 2.0 - See LICENSE
Author
GLINCKER Team
🌟 The most advanced natural language database query skill available!
1---2name: database-query3description: Natural language database queries with multi-database support, query optimization, and visual results4license: Apache-2.05---67# Database Query (Natural Language)89**⚡ UNIQUE FEATURE**: Query any database using natural language - automatically generates optimized SQL/NoSQL queries, explains query plans, suggests indexes, and visualizes results. Supports PostgreSQL, MySQL, MongoDB, SQLite, and more.1011## What This Skill Does1213Transform natural language into optimized database queries:1415- **Natural language to SQL**: "Show me users who signed up last month" → `SELECT * FROM users WHERE created_at >= NOW() - INTERVAL '1 month'`16- **Multi-database support**: PostgreSQL, MySQL, MongoDB, SQLite, Redis17- **Query optimization**: Analyzes queries and suggests improvements18- **Index suggestions**: Recommends indexes for slow queries19- **Visual results**: Formats query results as tables, charts, JSON20- **Query explanation**: EXPLAIN ANALYZE with human-readable insights21- **Safe mode**: Read-only by default with confirmation for writes22- **Schema discovery**: Auto-learns database structure2324## Why This Is Unique2526First Claude Code skill that:27- **Understands intent**: Translates vague requests to precise queries28- **Cross-database compatible**: Same natural language works across SQL/NoSQL29- **Performance-aware**: Automatically optimizes and suggests indexes30- **Safety-first**: Prevents destructive operations without confirmation31- **Learning mode**: Improves by understanding your schema3233## Instructions3435### Phase 1: Database Connection & Discovery36371. **Identify Database**:38 ```39 Ask user:40 - Database type (PostgreSQL, MySQL, MongoDB, SQLite, etc.)41 - Connection method (local, remote, Docker, MCP server)42 - Connection string or credentials43 ```44452. **Test Connection**:46 ```bash47 # PostgreSQL48 psql -h localhost -U user -d database -c "SELECT version();"4950 # MySQL51 mysql -h localhost -u user -p database -e "SELECT VERSION();"5253 # MongoDB54 mongosh "mongodb://localhost:27017/database" --eval "db.version()"5556 # SQLite57 sqlite3 database.db "SELECT sqlite_version();"58 ```59603. **Discover Schema**:61 ```bash62 # PostgreSQL: Get all tables and columns63 psql -d database -c "\dt"64 psql -d database -c "\d+ table_name"6566 # MySQL: Show database structure67 mysql database -e "SHOW TABLES;"68 mysql database -e "DESCRIBE table_name;"6970 # MongoDB: List collections and sample documents71 mongosh database --eval "db.getCollectionNames()"72 mongosh database --eval "db.collection.findOne()"73 ```74754. **Build Schema Cache**:76 - Store table/collection names77 - Store column names and types78 - Store relationships (foreign keys)79 - Cache common queries8081### Phase 2: Natural Language to Query Translation8283When user makes a request:84851. **Parse Intent**:86 ```87 Analyze the request:88 - Action: SELECT, INSERT, UPDATE, DELETE, aggregation89 - Entities: Which tables/collections90 - Conditions: WHERE clauses91 - Aggregations: COUNT, SUM, AVG, GROUP BY92 - Sorting: ORDER BY93 - Limits: TOP N, pagination94 ```95962. **Generate Query**:9798 **Example 1**: "Show me all active users"99 ```sql100 -- PostgreSQL/MySQL101 SELECT * FROM users WHERE status = 'active';102 ```103104 **Example 2**: "Count orders by status for last 7 days"105 ```sql106 SELECT status, COUNT(*) as count107 FROM orders108 WHERE created_at >= NOW() - INTERVAL '7 days'109 GROUP BY status110 ORDER BY count DESC;111 ```112113 **Example 3**: "Find top 10 customers by revenue"114 ```sql115 SELECT116 c.name,117 c.email,118 SUM(o.total) as revenue119 FROM customers c120 JOIN orders o ON c.id = o.customer_id121 GROUP BY c.id, c.name, c.email122 ORDER BY revenue DESC123 LIMIT 10;124 ```125126 **Example 4**: MongoDB aggregation127 ```javascript128 db.orders.aggregate([129 { $match: { status: "completed" } },130 { $group: {131 _id: "$customer_id",132 total: { $sum: "$amount" }133 }},134 { $sort: { total: -1 } },135 { $limit: 10 }136 ])137 ```1381393. **Validate Query**:140 - Check table/column names exist141 - Verify data types match142 - Ensure joins are valid143 - Detect potentially dangerous operations144145### Phase 3: Query Optimization146147Before execution:1481491. **Analyze Query Plan**:150 ```sql151 -- PostgreSQL152 EXPLAIN ANALYZE153 SELECT * FROM users WHERE email LIKE '%@example.com';154 ```1551562. **Suggest Optimizations**:157 ```158 If sequential scan detected:159 - "This query is scanning all rows. Consider adding an index:"160 - CREATE INDEX idx_users_email ON users(email);161162 If N+1 query pattern:163 - "Use JOIN instead of multiple queries"164 - Show optimized version165166 If missing WHERE clause:167 - "This will return all rows. Add filters or LIMIT?"168 ```1691703. **Rewrite for Performance**:171 ```sql172 -- Before (slow)173 SELECT * FROM users WHERE LOWER(email) = 'user@example.com';174175 -- After (fast - uses index)176 SELECT * FROM users WHERE email = 'user@example.com';177 ```178179### Phase 4: Safe Execution1801811. **Determine Query Type**:182 - **Read-only** (SELECT): Execute immediately183 - **Write** (INSERT, UPDATE, DELETE): Ask confirmation184 - **DDL** (CREATE, DROP, ALTER): Require explicit confirmation1851862. **Confirmation for Writes**:187 ```188 ⚠️ This query will modify data:189190 UPDATE users SET status = 'inactive'191 WHERE last_login < '2024-01-01'192193 Estimated affected rows: 1,247194195 Proceed? [yes/no]196 ```1971983. **Transaction Support**:199 ```sql200 BEGIN;201 -- Execute query202 -- Show results203 -- Ask: COMMIT or ROLLBACK?204 ```205206### Phase 5: Results Formatting2072081. **Table Format** (default):209 ```210 ┌────┬─────────────┬──────────────────────┬──────────┐211 │ id │ name │ email │ status │212 ├────┼─────────────┼──────────────────────┼──────────┤213 │ 1 │ John Doe │ john@example.com │ active │214 │ 2 │ Jane Smith │ jane@example.com │ active │215 └────┴─────────────┴──────────────────────┴──────────┘216217 2 rows returned in 0.023s218 ```2192202. **Chart Format** (for aggregations):221 ```222 Orders by Status:223224 pending ████████████░░░░░░░░ 62225 completed ████████████████████ 128226 cancelled ████░░░░░░░░░░░░░░░░ 15227 ```2282293. **JSON Format** (for APIs):230 ```json231 {232 "query": "SELECT * FROM users LIMIT 2",233 "execution_time": "0.023s",234 "row_count": 2,235 "results": [236 {"id": 1, "name": "John Doe", ...},237 {"id": 2, "name": "Jane Smith", ...}238 ]239 }240 ```2412424. **Export Options**:243 - CSV file244 - JSON file245 - Markdown table246 - Copy to clipboard247248## Examples249250### Example 1: Simple Query251252**User**: "Show me recent users"253254**Skill**:2551. Interprets "recent" as last 7 days2562. Generates query:257 ```sql258 SELECT * FROM users259 WHERE created_at >= NOW() - INTERVAL '7 days'260 ORDER BY created_at DESC;261 ```2623. Executes and displays results2634. Suggests: "Want to filter by status or role?"264265### Example 2: Complex Aggregation266267**User**: "Which products had the most revenue last quarter?"268269**Skill**:2701. Determines tables: products, orders, order_items2712. Calculates "last quarter" date range2723. Generates optimized query:273 ```sql274 SELECT275 p.id,276 p.name,277 SUM(oi.quantity * oi.price) as revenue,278 COUNT(DISTINCT o.id) as order_count279 FROM products p280 JOIN order_items oi ON p.id = oi.product_id281 JOIN orders o ON oi.order_id = o.id282 WHERE o.created_at >= DATE_TRUNC('quarter', NOW() - INTERVAL '3 months')283 AND o.created_at < DATE_TRUNC('quarter', NOW())284 AND o.status = 'completed'285 GROUP BY p.id, p.name286 ORDER BY revenue DESC287 LIMIT 10;288 ```2894. Shows results with chart2905. Offers to export291292### Example 3: Performance Investigation293294**User**: "Why is this query slow?"295```sql296SELECT * FROM orders WHERE customer_name LIKE 'John%';297```298299**Skill**:3001. Runs EXPLAIN ANALYZE3012. Detects: Sequential scan on 10M rows3023. Suggests:303 ```304 ⚠️ Performance Issue Detected:305306 Problem: Full table scan (10,485,234 rows)307 Solution: Add an index on customer_name308309 CREATE INDEX idx_orders_customer_name ON orders(customer_name);310311 Expected improvement: 10,485,234 rows → ~42 rows312 Estimated speed-up: 10,000x faster313314 Would you like me to create this index?315 ```316317## Configuration318319Create `.database-query-config.yml`:320321```yaml322databases:323 - name: production324 type: postgresql325 host: localhost326 port: 5432327 database: myapp328 user: readonly_user329 ssl: true330 read_only: true331332 - name: analytics333 type: mongodb334 uri: mongodb://localhost:27017/analytics335336 - name: cache337 type: redis338 host: localhost339 port: 6379340341defaults:342 max_rows: 1000343 timeout: 30s344 explain_threshold: 1s # Auto-explain queries slower than 1s345 auto_optimize: true346347safety:348 require_confirmation_for_writes: true349 prevent_drop_table: true350 max_affected_rows: 10000351```352353## Tool Requirements354355- **Bash**: Execute database CLI commands356- **Read**: Read config files and schema cache357- **Write**: Save query results and reports358- **Task**: Launch optimization analyzer agent359360## Integration with MCP361362Connect to MCP database servers:363364```yaml365# Using PostgreSQL MCP server366mcp_servers:367 - name: postgres368 command: postgres-mcp369 args:370 - --connection-string371 - postgresql://user:pass@localhost/db372```373374## Advanced Features375376### 1. Query History & Favorites377378```bash379# Save favorite queries380claude db save "monthly_revenue" "SELECT..."381382# Run saved query383claude db run monthly_revenue384```385386### 2. Query Templates387388```sql389-- Template: user_search390SELECT * FROM users391WHERE {{field}} = {{value}}392AND status = 'active';393```394395### 3. Data Migration Helper396397```python398# Generate migration between databases399claude db migrate --from postgres://... --to mysql://...400```401402### 4. Schema Diff403404```bash405# Compare two databases406claude db diff production staging407```408409## Best Practices4104111. **Start with schema**: Let skill discover your database first4122. **Use read-only mode**: For production databases4133. **Review before writes**: Always check UPDATE/DELETE affects4144. **Monitor performance**: Pay attention to optimization suggestions4155. **Save common queries**: Build a library of frequently-used queries4166. **Use transactions**: For multi-step operations417418## Limitations419420- Maximum 10,000 rows displayed (configurable)421- Query timeout: 30 seconds (configurable)422- Write operations require confirmation423- Some database-specific features may not translate424- Complex stored procedures not supported425426## Security427428- Never stores credentials in plain text429- Read-only mode by default430- SQL injection prevention431- Confirms destructive operations432- Audit logging available433434## Related Skills435436- [api-connector](../api-connector/SKILL.md) - Query APIs with natural language437- [data-analyzer](../../data-science/data-analyzer/SKILL.md) - Analyze query results438- [schema-designer](../../development/schema-designer/SKILL.md) - Design database schemas439440## Changelog441442### Version 1.0.0 (2025-01-13)443- Initial release444- PostgreSQL, MySQL, MongoDB, SQLite support445- Natural language query translation446- Query optimization and EXPLAIN447- Multiple output formats448- Safe mode with confirmations449450## Contributing451452Help expand database support:453- Add new database types (CockroachDB, DynamoDB, Cassandra)454- Improve query optimization455- Add more visualization options456- Create query templates457458## License459460Apache License 2.0 - See [LICENSE](../../../LICENSE)461462## Author463464**GLINCKER Team**465- GitHub: [@GLINCKER](https://github.com/GLINCKER)466- Repository: [claude-code-marketplace](https://github.com/GLINCKER/claude-code-marketplace)467468---469470**🌟 The most advanced natural language database query skill available!**