Navigating the True Boundaries of AI Agents in SQL Generation and Selection

    As LLM API prices decrease, AI programming agents for SQL generation are becoming more accessible. However, lower invocation costs do not guarantee production-ready outputs. This article explores the phenomenon of "constraint decay," where AI struggles to maintain complex organizational requirements like permissions, tenant isolation, and audit standards. It outlines a total cost of ownership (TCO) model for evaluation, proposes a tiered benchmarking approach (L1-L5) for vendor selection, and provides engineering best practices to transform natural language constraints into executable gateways, ensuring verifiable and compliant SQL delivery.

    Recently, model API prices have continued to drop, making AI programming agents seem more affordable. However, for data teams, lower costs only solve the barrier to entry; they do not automatically resolve a more critical issue: whether the generated SQL is truly deliverable. Asking an AI to write a single-table query or a simple aggregation usually works fine. But once a task involves corporate naming conventions, permission systems, tenant isolation, audit requirements, sensitive field masking, multi-table JOINs, and performance limits, the agent may lose constraints during multi-turn generation. This leads to situations where the “syntax runs, but the semantics are wrong, permissions are non-compliant, and performance is unacceptable.”

    The core issue behind this can be summarized as “constraint decay”: when a task includes multiple hard conditions simultaneously, the model must continuously maintain these conditions across long contexts and multiple tool calls. As metadata increases, instructions lengthen, and repair rounds accumulate, early constraints are easily diluted. Conflicting instructions are often handled based on the model’s preference to “just get the SQL running.” The price war changes the cost curve, but capability boundaries still need to be confirmed through engineering evaluation and guardrails.

    1. Price Drops Do Not Equal Capability Compliance

    The significant reduction in model API prices directly lowers experimental costs for data teams: it is cheaper to generate SQL drafts, explain fields, fix errors, and complete documentation. However, the unit task cost of an AI programming agent is not just the fee for a single model call. It also includes metadata retrieval, tool invocation, retries, manual review, failure regression, and potential incident costs.

    Simple SQL tasks have a short call chain and a high cache reuse rate, making cost reductions highly noticeable. Complex multi-table JOINs, on the other hand, often require reading table structures, field semantics, partition info, permission policies, and audit standards, followed by execution parsing, policy checking, and execution plan verification. If a generation fails, retries continue to incur call costs, and manual rework consumes higher labor costs. Therefore, evaluating an AI programming agent should not focus solely on “cost per million tokens,” but on the “total cost of ownership (TCO) per deliverable SQL task.”

    For data teams, a reasonable cost model should at least include:

    • Single generation cost: Model calls, context retrieval, tool invocations.
    • Retry cost: Rounds of syntax repair, semantic repair, and constraint repair.
    • Verification cost: SQL parsing, metadata validation, permission policy checks, execution plan reviews.
    • Review cost: Time spent manually reviewing high-risk SQL.
    • Incident cost: Governance costs from privilege escalation, sensitive data leakage, full-table scans, or erroneous writes.

    Price reductions are welcome, but price should only be one variable in the selection process, not the only one.

    2. Constraint Decay: Why Complex SQL is More Prone to Failure

    SQL is a declarative language; on the surface, it looks like “just writing a query,” but it actually embeds organizational-level constraints. A production-ready SQL task may contain at least the following constraint stack:

    1. Syntax and dialect constraints: Whether functions, type conversions, date handling, and window functions align with the target engine.
    2. Metadata constraints: Accuracy of table names, field names, types, partition fields, primary keys, and relationships.
    3. Naming convention constraints: Whether database/table aliases, field aliases, and temporary table names comply with team standards.
    4. Permission and security constraints: Involvement of row-level permissions, column-level permissions, tenant isolation, and sensitive field masking.
    5. Audit constraints: Inclusion of necessary audit fields, operation sources, and time ranges.
    6. Performance constraints: Avoiding full-table scans, limiting partition scopes, and ensuring logical JOIN orders.
    7. Write safety constraints: Whether write operations feature idempotency, transaction boundaries, and rollback plans.
    8. Explainability constraints: Whether the SQL can be traced back to business metrics and data lineage.

    When a task includes only one or two constraints, the model easily satisfies them. When constraints accumulate to five or six, the model must maintain multiple “hard conditions” within a long context. If the prompt contains natural language specifications, metadata snippets, and historical repair feedback, the model might prioritize “generating a query that looks correct” while ignoring hard requirements like “must include tenant field,” “must limit partition scope,” or “must use the audit view.”

    Crucially, when SQL tasks lack automated feedback, errors often remain invisible. Syntax errors are easily caught, but semantic and permission errors might not surface until deployment. For instance, the model generates an executable JOIN query but omits the tenant isolation condition; or it uses a base table instead of a permissioned view; or field aliases violate conventions, causing confusion in downstream reporting metrics. These issues are not a matter of the model “not knowing how to write SQL,” but rather the model “failing to consistently pass assertions across the constraint stack.”

    3. Do Not Use “Write a SQL Query” for Selection

    When evaluating AI programming agents, the least reliable method is asking it to write a simple query on the spot and scoring it based on subjective impressions. A better approach is to build a tiered benchmark set, breaking down “capability” into verifiable assertions.

    Tasks can be designed across five complexity levels:

    • L1: Single-table queries, filtering, sorting, aggregation.
    • L2: Multi-table JOINs, subqueries, window functions, metric calculations.
    • L3: Queries with naming conventions, permission views, tenant isolation, and audit fields.
    • L4: Performance-sensitive queries with partition limits, execution plan checks, and scan volume constraints.
    • L5: Failure repair and regression, including whether it can fix errors based on provided messages without breaking original constraints.

    Each tier should be equipped with assertions, rather than just inspecting the final SQL text. An example configuration looks like this:

    1. task: multi_table_join_with_policy
    2. constraints:
    3. naming: "Aliases and field aliases comply with team conventions"
    4. tenant_isolation: "Must include tenant filter conditions"
    5. audit: "Must retain audit time fields"
    6. partition: "Must limit partition scope"
    7. assertions:
    8. - type: sql_parse
    9. - type: metadata_check
    10. - type: policy_check
    11. - type: partition_filter_check
    12. - type: explain_scan_limit
    13. - type: audit_column_present
    14. metrics:
    15. - syntax_pass_rate
    16. - constraint_pass_rate
    17. - repair_rounds
    18. - human_rework_rate
    19. - total_cost_per_deliverable_sql

    The key to this configuration is not to achieve a specific score, but to give the team clarity: How does the agent’s pass rate change as constraints accumulate? Are repair rounds controllable? Which constraints are most frequently lost? Which errors absolutely require manual review fallback?

    4. Engineering Implementation: Turn Specifications into Executable Gateways

    To reduce failures, you cannot rely solely on longer prompts; you must turn constraints from natural language into executable gateways. Consider starting with the following areas:

    First, on-demand metadata retrieval. Do not stuff the entire database schema into the context at once. Instead, perform intent recognition and table candidate recall first, then load field semantics, partition info, permissioned views, and relationships on demand. The cleaner the context, the less likely constraints are to be diluted.

    Second, rule-based standardization. Naming conventions, permission requirements, audit fields, and partition limits should be written as policy files and checkers. The agent’s output should be automatically checked, rather than relying solely on prompt reminders. The prompt expresses intent; the checker guards the baseline.

    Third, phased generation. Break the task into stages: “understand intent and select tables — generate draft SQL — permission and audit check — performance check — manual review.” Each stage should have clear outputs and assertions, avoiding the difficulty of locating issues after generating complex SQL in one go.

    Fourth, build a regression set. Accumulate historical failure samples, sensitive field samples, cross-tenant samples, and full-table scan samples as regression test cases. Whenever you switch models, adjust prompts, or upgrade the agent workflow, run the regression set to observe constraint pass rates and repair rounds.

    Fifth, focus manual review on high-risk areas. Write operations, cross-tenant queries, sensitive field access, large partition scans, and financially relevant SQL should mandate manual review. Low-risk read-only queries can rely more on automated assertions.

    Sixth, retain observable traces. Record prompts, retrieved metadata, generated SQL, assertion results, repair feedback, and final review conclusions. This enables auditing and helps pinpoint whether an issue stems from model capability, metadata, or rule configuration.

    5. Selection Checklist: From Demo Effects to Verifiable Productivity

    When data teams select an AI programming agent, it is recommended to evaluate at least the following dimensions:

    1. Pass rate under complex constraints: Look beyond simple queries to performance under combined multi-table JOINs, permissioned views, tenant isolation, and audit fields.
    2. Verifiability: How easily it integrates with general gateways like SQL parsing, metadata validation, policy checking, and execution plan reviews.
    3. Governability: Whether it supports logging, permission control, audit tracking, and sensitive operation review.
    4. Integration: Whether it can connect with existing metadata management, policy systems, CI/CD pipelines, and monitoring alerts.
    5. Cost structure: Factoring invocation, retry, verification, manual review, and incident costs into the TCO.
    6. Compliance and deployment: Whether it meets requirements for data sovereignty, permission isolation, and auditing.

    If teams are already using Baidu AI Cloud, they can incorporate general cloud components such as model services, logging, monitoring, and permission systems into a unified governance evaluation. However, the focus should remain on actual benchmark testing and verifiability, rather than on a single price point or demo effect.

    6. Conclusion

    The boundary of AI programming agents writing SQL is not whether they can generate a SELECT statement, but whether they can consistently pass assertions as constraints accumulate. Price drops make experimentation cheaper, but production delivery requires “verifiable productivity.” Data teams should shift selection from live demos to tiered benchmarks, shift specifications from prompts to externalized rules, and shift costs from single calls to total cost of ownership. Only when naming conventions, permission systems, audit requirements, and performance limits become executable gateways can AI-generated SQL transition from “capable of writing” to “deliverable.”