$npx -y skills add langchain-ai/deepagents --skill query-writingWrites and executes SQL queries from simple SELECTs to complex multi-table JOINs, aggregations, and subqueries. Use when the user asks to query a database, write SQL, run a SELECT statement, retrieve data, filter records, or generate reports from database tables.
| 1 | # Query Writing Skill |
| 2 | |
| 3 | ## Workflow for Simple Queries |
| 4 | |
| 5 | For straightforward questions about a single table: |
| 6 | |
| 7 | 1. **Identify the table** - Which table has the data? |
| 8 | 2. **Get the schema** - Use `sql_db_schema` to see columns |
| 9 | 3. **Write the query** - SELECT relevant columns with WHERE/LIMIT/ORDER BY |
| 10 | 4. **Execute** - Run with `sql_db_query` |
| 11 | 5. **Format answer** - Present results clearly |
| 12 | |
| 13 | ## Workflow for Complex Queries |
| 14 | |
| 15 | For questions requiring multiple tables: |
| 16 | |
| 17 | ### 1. Plan Your Approach |
| 18 | **Use `write_todos` to break down the task:** |
| 19 | - Identify all tables needed |
| 20 | - Map relationships (foreign keys) |
| 21 | - Plan JOIN structure |
| 22 | - Determine aggregations |
| 23 | |
| 24 | ### 2. Examine Schemas |
| 25 | Use `sql_db_schema` for EACH table to find join columns and needed fields. |
| 26 | |
| 27 | ### 3. Construct Query |
| 28 | - SELECT - Columns and aggregates |
| 29 | - FROM/JOIN - Connect tables on FK = PK |
| 30 | - WHERE - Filters before aggregation |
| 31 | - GROUP BY - All non-aggregate columns |
| 32 | - ORDER BY - Sort meaningfully |
| 33 | - LIMIT - Default 5 rows |
| 34 | |
| 35 | ### 4. Validate and Execute |
| 36 | Check all JOINs have conditions, GROUP BY is correct, then run query. |
| 37 | |
| 38 | ## Example: Revenue by Country |
| 39 | ```sql |
| 40 | SELECT |
| 41 | c.Country, |
| 42 | ROUND(SUM(i.Total), 2) as TotalRevenue |
| 43 | FROM Invoice i |
| 44 | INNER JOIN Customer c ON i.CustomerId = c.CustomerId |
| 45 | GROUP BY c.Country |
| 46 | ORDER BY TotalRevenue DESC |
| 47 | LIMIT 5; |
| 48 | ``` |
| 49 | |
| 50 | ## Error Recovery |
| 51 | |
| 52 | If a query fails or returns unexpected results: |
| 53 | 1. **Empty results** — Verify column names and WHERE conditions against the schema; check for case sensitivity or NULL values |
| 54 | 2. **Syntax error** — Re-examine JOINs, GROUP BY completeness, and alias references |
| 55 | 3. **Timeout** — Add stricter WHERE filters or LIMIT to reduce result set, then refine |
| 56 | |
| 57 | ## Quality Guidelines |
| 58 | |
| 59 | - Query only relevant columns (not SELECT *) |
| 60 | - Always apply LIMIT (5 default) |
| 61 | - Use table aliases for clarity |
| 62 | - For complex queries: use write_todos to plan |
| 63 | - Never use DML statements (INSERT, UPDATE, DELETE, DROP) |