Query Writing

langchain-ai/deepagents/examples/text-to-sql-agent/skills/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 从公开仓库中收录这些内容。

举报或申请下架