Why Cheaper AI Coding Agents Still Struggle With Complex SQL
Lower model-call costs make it easier for teams to use AI coding agents for query writing, data-cleaning scripts, and tests, but lower cost does not automatically solve correctness. This article explains “constraint decay” in complex SQL tasks, where explicit, structural, and governance requirements accumulate and the agent satisfies some rules while missing others. It examines five common failure modes, recommends data-first analysis, layered generation, validation SQL, and automated quality gates, and outlines which tasks should remain under human ownership and how to evaluate coding tools against real data work.
AI coding agents have become rapidly cheaper to use, while invocation speed, context length, and code-generation capability continue to improve. For data analysts, data engineers, and development teams, using agents to write queries, generate data-cleaning scripts, and add test cases has gradually moved from experimentation to a common way of working.
But there is an easily overlooked fact: lower tool prices only reduce the barrier to use. They do not automatically solve the correctness problem.
Asking an agent to generate a simple query is usually not difficult:
SELECT user_id, order_amountFROM ordersWHERE order_date >= '2025-01-01';
The real difficulty is satisfying dozens of implicit rules within a single task, for example:
- Table and field names must follow enterprise naming conventions.
- Amount fields must consistently use the financial settlement basis.
- User data must be de-identified.
- Order statuses must be mapped according to the business dictionary.
- Multi-table joins must use designated primary keys.
- Queries must not access restricted fields.
- Results must preserve an audit trail.
- SQL must be compatible with the specified database dialect.
- Query cost must stay within the resource budget.
- Metric results must remain consistent with historical reports.
As these constraints accumulate, agents often do not fail because they “cannot write SQL at all.” Instead, they produce something that looks locally reasonable but does not satisfy the requirements as a whole. The final symptoms can include: the SQL runs, but the result cannot be trusted; the result looks correct, but it violates permission or audit requirements; or unit tests pass, but serious deviations appear under real data distributions.
This is the phenomenon known as constraint decay in complex tasks.
1. Why Cheap Does Not Mean Reliable
The cost of intelligent coding tools is usually determined by model calls, input and output length, cache hits, and task complexity. After call costs fall, teams can involve agents more frequently in code generation, bug fixing, and approach exploration. That is valuable for improving development efficiency.
But cost and quality are different dimensions:
- Cost answers: “How many resources does one use consume?”
- Capability answers: “Does the generated result meet the task requirements?”
- Reliability answers: “Will the result hold up consistently across different data and environments?”
- Governability answers: “Can the process be audited, rolled back, and attributed?”
For simple tasks, all four may perform well at the same time. For example, adding a field filter or implementing a basic function is easy to verify, and errors are relatively cheap to fix.
Complex data tasks are different. A SQL statement may contain a dozen tables, multiple common table expressions, window functions, nested aggregations, and complex time semantics. At that point, missing any single constraint can change the final result. More importantly, syntactically valid SQL does not mean semantically correct SQL.
For example, both of the following statements can execute:
SELECT COUNT(*)FROM ordersWHERE status = 'paid';
SELECT COUNT(DISTINCT order_id)FROM order_eventsWHERE event_type = 'payment_success';
They may represent “the number of paid orders” and “the number of distinct orders involved in successful payment events,” respectively. If duplicate events, compensation records, or order splits exist, the two results can differ. If an agent does not understand the metric definition and guesses only from field names, it can easily produce SQL that runs but is inaccurate.
2. Why Constraints Gradually Fail
When generating code, an agent usually needs to combine three types of information.
2.1 Explicit requirements
These are requirements the user directly states, such as:
- Query the last three months of data.
- Calculate revenue by department.
- Exclude canceled orders.
- Output month-over-month changes.
Explicit requirements are usually easy for a model to capture, and they are the easiest to check superficially.
2.2 Structural constraints
Structural constraints come from database and engineering standards, such as:
- Which table is the fact table.
- Which fields are primary keys.
- Which fields are allowed in joins.
- Which time zone the time fields use.
- Which intermediate model the result must pass through.
- Whether direct access to detail tables is allowed.
This information is often scattered across data dictionaries, modeling documents, historical SQL, and code repositories. Users do not repeat all of it in every request.
2.3 Organizational and governance constraints
Governance constraints include:
- Sensitive fields must not appear in results.
- Queries must include partition predicates.
- Certain data may only be accessed by authorized roles.
- All metrics must record the definition version.
- Production queries require approval.
- Resource consumption must not exceed a defined limit.
These requirements often do not appear in SQL syntax, yet they directly determine whether a task can go live.
As the number of constraints increases, an agent may prioritize explicit requirements while gradually ignoring structural and governance requirements. The cause is not necessarily that the model “does not know SQL.” Rather, it may be unable to reliably maintain all context or determine which rules have higher priority.
3. The Five Most Common Failure Modes in Complex SQL
3.1 The right table, but the wrong metric definition
An agent can locate related tables based on field names, but it may not understand the business definition of a metric.
For example, “active user” may refer to users who logged in, users who made transactions, users who completed a key action, or users who are deduplicated within a certain time window. Different definitions correspond to different filters and deduplication strategies.
A better approach is to provide structured metric definitions rather than only a natural-language name:
Metric name: Monthly Active UsersEntity: UserTime field: activity_timePeriod: Calendar monthDeduplication: DISTINCT user_idInclusion criteria: Completed the specified business actionExclusion criteria: Test accounts, internal accounts
The clearer the definition, the less the agent needs to guess.
3.2 Correct JOIN logic, but data is duplicated and inflated
Multi-table joins are one of the most common sources of hidden errors in SQL generation.
Suppose the orders table and the order-items table have a one-to-many relationship, and the orders table also has a one-to-many relationship with a marketing-touch table. If all three tables are joined directly, order amounts may be counted multiple times. The SQL can execute successfully, but the aggregate result will be inflated.
Common safeguards include:
- Aggregate to the business grain before joining.
- State the primary key and grain of each table.
- Check one-to-many relationships for duplication.
- Avoid summing directly over unverified detail layers.
- Add total-value checks and sample reconciliation for key metrics.
An illustrative pattern is:
WITH item_summary AS (SELECTorder_id,SUM(item_amount) AS item_amountFROM order_itemsGROUP BY order_id)SELECTo.order_date,SUM(s.item_amount) AS total_amountFROM orders oJOIN item_summary sON o.order_id = s.order_idGROUP BY o.order_date;
The key here is not syntax. It is reducing the detail table to the order grain before performing later aggregation.
3.3 Time conditions look reasonable, but the boundaries are inconsistent
Time issues often cause a report to be one day short, one day long, or double-counted across months. Common risks include:
- Mixing local time and standard time.
- Using a closed interval at one boundary and an open interval at the other.
- Handling month-end, daylight saving time, or cross-time-zone cases inconsistently.
- Using update time instead of business occurrence time.
- Filtering only on a partition column without filtering the actual event time.
The safer pattern is usually a left-closed, right-open interval:
WHERE event_time >= '2025-01-01 00:00:00'AND event_time < '2025-02-01 00:00:00'
At the same time, the task specification should state the time zone, time field, and boundary rule rather than simply saying “query January data.”
3.4 Syntax is compatible, but the dialect is not
Different databases may differ in date functions, string handling, array types, window functions, and pagination syntax. If an agent generates code based only on general SQL knowledge, problems may include:
- Unsupported function names.
- Different type-conversion rules.
- Different null-handling behavior.
- Different identifier case sensitivity.
- Differences in recursive queries or window syntax.
- Execution plans that differ completely from expectations.
Therefore, the task must specify the target database type and version range, and the agent should be asked to list any non-generic syntax it uses. For production tasks, do not rely on static checks alone. Validate by executing in an isolated environment.
3.5 Permissions and data security are ignored
This is the problem least suited to manual visual inspection.
To complete an analysis, an agent may actively choose detail tables containing phone numbers, government ID identifiers, contact information, or internal tags. Even if those fields are not output in the final result, the query itself may violate the principle of least privilege.
Security constraints should be enforced at the execution layer:
- Restrict accessible tables through database permissions.
- Apply masking or column-level controls to sensitive fields.
- Check query results at the output boundary.
- Record the caller, task description, generated SQL, and execution results.
- Prohibit agents from connecting directly to production databases to execute unapproved statements.
- Set blocking rules for full-table scans, bulk exports, and high-resource queries.
Security requirements cannot exist only in a prompt. A prompt can help the agent understand the rules, but it cannot replace a permission system.
4. How to Reshape Complex Tasks So Agents Can Complete Them Reliably
Step 1: Have the agent understand the data before writing SQL
Ask it to output the following first:
- The business entities involved.
- The data grain of each table.
- Primary keys, foreign keys, and join relationships.
- Metric definitions.
- Time semantics.
- Steps that may create duplicates.
- Ambiguities that require human confirmation.
Only after this analysis is confirmed should the task move to SQL generation.
Step 2: Use layered generation
Do not ask the agent to generate the final query in one shot. Split the work into four layers:
- Business layer: Clarify metrics and filters.
- Data layer: Determine tables, fields, and join relationships.
- Logic layer: Design aggregation, deduplication, and window calculations.
- SQL layer: Convert the logic into the target database dialect.
Keep the intermediate output at each layer. When a problem appears, the team can determine whether it came from metric misunderstanding, table selection, or dialect conversion.
Step 3: Have the agent generate validation SQL at the same time
In addition to the main query, ask for supporting checks:
-- Check for duplicate ordersSELECT order_id, COUNT(*)FROM result_detailGROUP BY order_idHAVING COUNT(*) > 1;
-- Check for null key fieldsSELECT COUNT(*)FROM result_detailWHERE user_id IS NULL;
-- Check for abnormal negative amountsSELECT COUNT(*)FROM result_detailWHERE amount < 0;
The value of validation SQL is that it changes “I believe the result is correct” into “I can prove that several key conditions hold.”
Step 4: Establish automated quality gates
Before execution or merge, check at least the following:
- Does the query include the necessary time filter?
- Does it access sensitive fields?
- Does it contain an unconditional Cartesian product?
- Does it use unauthorized tables?
- Is there a risk of duplicate aggregation?
- Does it pass syntax parsing?
- Does it pass execution on a small sample?
- Does it meet resource-consumption limits?
- Is the difference from the baseline result within a reasonable range?
For core metrics, a dual implementation can also be used: have the agent generate one SQL version, then produce an independent version manually or through another set of rules, and compare the two on sample data and historical periods.
5. Which Tasks Are Suitable for Agents?
Tasks that are relatively suitable for automation include:
- Generating basic query templates.
- Converting natural language into an initial SQL query.
- Adding field comments and data dictionary entries.
- Generating repetitive validation statements.
- Converting SQL from one dialect to another.
- Analyzing obvious issues in an execution plan.
- Adding test cases to existing queries.
- Generating data-cleaning scripts from explicit rules.
The common characteristics of these tasks are clear input boundaries, low verification cost, and controllable impact from errors.
6. Which Tasks Must Preserve Human Decision-Making?
The following tasks should not be handed entirely to agents:
- Defining core business metrics.
- Deciding which data source is authoritative.
- Explaining the business reasons behind anomalous data.
- Designing cross-department permission boundaries.
- Approving high-risk queries in production.
- Handling data involving privacy and compliance.
- Modifying critical data models.
- Making major business judgments based on a single result.
Agents are good at generating candidate solutions, organizing information, and performing repetitive work. They should not replace the business owner who is accountable for definitions, risks, and results.
7. What to Look for When Choosing Intelligent Coding Tools
Do not compare only call prices or advertised code pass rates. Build an evaluation system oriented toward real work:
- Correctness: Does the result match the metric definition?
- Stability: Does the same task produce consistent results across multiple generations?
- Constraint adherence: Can it satisfy naming, permission, and architecture requirements at the same time?
- Explainability: Can it explain table selection, join relationships, and aggregation logic?
- Verifiability: Can it proactively generate tests and checks?
- Governability: Does it support logs, approvals, rollback, and permission isolation?
- Context management: Can it effectively use data dictionaries, standards documents, and historical cases?
- Human takeover cost: Is the generated result easy for engineers to review and modify?
Use real enterprise tasks that have been de-identified, covering scenarios such as simple queries, complex joins, metric calculations, permission controls, and performance optimization. Only then will the evaluation results have practical reference value.
Conclusion: The Goal Is Reliable Collaboration Within Boundaries, Not Letting the Agent Write Everything
Lower costs for intelligent coding agents will allow more teams to use them. But reliable generation of complex SQL has never depended only on model capability. It also depends on clear data definitions, complete metadata, an enforceable permission system, automated testing, and a strict release process.
The most reasonable way to position an agent is neither as an “infallible programmer” nor as something to reject entirely because it occasionally makes mistakes. It is an efficient collaborator that requires supervision.
Simple tasks can be generated directly; complex tasks must be decomposed. Syntax can be checked automatically; business definitions must be confirmed by humans. Agents can propose results; production execution must go through governance. Costs can continue to fall, but the quality bar must not fall with them.
Only by placing agents inside a complete engineering workflow can data teams gain real efficiency benefits, rather than receiving a batch of SQL that looks professional but is difficult to hold accountable in practice.
