Query Writing

作者 langchain-ai6a3a12bc5b3a無授權條款30K 個星標收錄於 2026年10月8日更新於 2026年10月8日儲存庫今天更新

Writes 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.

僅含說明Data & Analytics
AI 產生的概覽

指導撰寫與執行 SQL 查詢,涵蓋簡單 SELECT 到多表 JOIN 與聚合。

功能
此技能提供將資料問題轉換為 SQL 的逐步流程:找出資料表、檢視結構、撰寫查詢、執行並清楚呈現結果。它涵蓋單一資料表的簡單查詢,以及包含 JOIN、GROUP BY 聚合、子查詢、篩選、排序與限制的多資料表複雜查詢。它也包含針對空結果、語法錯誤與逾時的錯誤復原指引,以及避免 SELECT *、禁止使用 DML 語句等品質規則。
適用情境
當使用者要求查詢資料庫、撰寫 SQL、執行 SELECT 語句、擷取或篩選紀錄,或根據資料庫資料表產生報表時使用。它同時適用於簡單的單一資料表查詢,以及需要串接多個資料表的問題。
執行需求
需要資料庫連線,以及 sql_db_schema 與 sql_db_query 工具,複雜查詢規劃還需 write_todos。不隨附指令碼,僅為說明文件。

Query Writing Skill

Workflow for Simple Queries

For straightforward questions about a single table:

  1. Identify the table - Which table has the data?
  2. Get the schema - Use sql_db_schema to see columns
  3. Write the query - SELECT relevant columns with WHERE/LIMIT/ORDER BY
  4. Execute - Run with sql_db_query
  5. Format answer - Present results clearly

Workflow for Complex Queries

For questions requiring multiple tables:

1. Plan Your Approach

Use write_todos to break down the task:

  • Identify all tables needed
  • Map relationships (foreign keys)
  • Plan JOIN structure
  • Determine aggregations

2. Examine Schemas

Use sql_db_schema for EACH table to find join columns and needed fields.

3. Construct Query

  • SELECT - Columns and aggregates
  • FROM/JOIN - Connect tables on FK = PK
  • WHERE - Filters before aggregation
  • GROUP BY - All non-aggregate columns
  • ORDER BY - Sort meaningfully
  • LIMIT - Default 5 rows

4. Validate and Execute

Check all JOINs have conditions, GROUP BY is correct, then run query.

Example: Revenue by Country

sql
SELECT    c.Country,    ROUND(SUM(i.Total), 2) as TotalRevenueFROM Invoice iINNER JOIN Customer c ON i.CustomerId = c.CustomerIdGROUP BY c.CountryORDER BY TotalRevenue DESCLIMIT 5;

Error Recovery

If a query fails or returns unexpected results:

  1. Empty results — Verify column names and WHERE conditions against the schema; check for case sensitivity or NULL values
  2. Syntax error — Re-examine JOINs, GROUP BY completeness, and alias references
  3. Timeout — Add stricter WHERE filters or LIMIT to reduce result set, then refine

Quality Guidelines

  • Query only relevant columns (not SELECT *)
  • Always apply LIMIT (5 default)
  • Use table aliases for clarity
  • For complex queries: use write_todos to plan
  • Never use DML statements (INSERT, UPDATE, DELETE, DROP)

來源與署名

來源:langchain-ai/deepagents位於examples/text-to-sql-agent/skills/query-writing提交6a3a12b

授權條款: 無授權條款

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架