AI Coding Agents Can Write SQL—So Why Do They Fail Under Complex Constraints?
AI coding agents have become dramatically cheaper to use, but cost isn't the same as capability. Recent research on "constraint decay" shows that as structured requirements—naming conventions, ORM mappings, architectural rules—accumulate, agent performance drops sharply, with assertion pass rates falling roughly 30 percentage points. This article explains why SQL generation is especially vulnerable to this failure mode, and offers practical strategies for teams: phased constraint delivery, machine-checkable standards, layered human-AI workflows, and constraint-aware tool evaluation.
Background: Falling Costs, Unchanged Technical Limits
Over the past year, the cost of calling large language models has dropped by orders of magnitude. Multiple vendors have cut API pricing, while caching mechanisms and batch billing have further reduced inference expenses. For data teams, this has turned “using AI to write SQL and data processing scripts” from an expensive experiment into an everyday capability.
But cheap doesn’t mean reliable. A widely discussed recent academic study revealed a notable phenomenon: as structural constraints in requirements gradually accumulate, the performance of AI coding agents declines significantly. Through end-to-end behavioral testing across multiple web frameworks, combined with a static validator for dual evaluation, the researchers found that as requirements for naming conventions, ORM mappings, and architectural constraints stack up, agents’ assertion pass rates drop by roughly 30 percentage points on average—and under weak configurations, performance approaches total failure.
Translated into a data analyst’s language: asking AI to write a simple SELECT statement is fine. But asking it to follow your company’s naming conventions, permission system, and audit requirements while writing a five-table JOIN query? It will most likely fail.
What Is “Constraint Decay”?
Defining the Phenomenon
Constraint decay refers to this: a model can follow an individual constraint when it’s presented alone, but when multiple constraints appear simultaneously or accumulate, the model’s ability to remember and execute earlier constraints visibly degrades.
An intuitive analogy: a human developer can strictly execute a two-page requirements document, but if that document keeps growing to twenty pages—full of interrelated detailed rules—omissions and conflicts become inevitable. Language models have a similar capacity and attention-allocation problem: the longer the context and the more constraints involved, the more likely early instructions are to get “diluted.”
What the Experimental Evidence Teaches Us
Several aspects of the study’s experimental design are worth learning from:
- Task layering: simple tasks established a baseline of capability, while complex tasks tested constraint capacity;
- Dual evaluation: the researchers checked both runtime behavior against expectations and used a static checker to verify code compliance, avoiding the false positives of “if it runs, it’s fine”;
- Framework sensitivity: agents performed well in minimalist frameworks with few rules and simple conventions, but performance dropped markedly in convention-heavy frameworks with many implicit rules.
The mapping to data analysis scenarios is direct. SQL is itself a “convention-dense” language: dialect differences (window function syntax, date functions, type casting rules), internal data-layering standards (layered architecture conventions like ODS/DWD/DWS/ADS), field naming prefixes, partitioning requirements, and data-masking rules for sensitive data—none of these appear in your natural-language prompt, but all of them show up on the review checklist.
Why SQL Generation Is Especially Prone to Failure
1. Context Is Disconnected from the Real Data Environment
Most SQL in model training corpora comes from public tutorials and examples, using standardized table names and data types. The actual table structures, field semantics, and data-skew conditions in enterprise environments are unknown to the model. A syntactically correct query can produce wrong results on real data due to implicit type conversions, NULL semantics, or timezone handling—this kind of “semantic failure” is far more insidious than a syntax error.
2. The Stacking Effect of Constraints
A production-grade SQL query typically carries multiple layers of constraints at once:
- Syntax layer: correct JOIN conditions, avoiding Cartesian products;
- Performance layer: partition pruning, predicate pushdown, avoiding full scans of large tables;
- Standards layer: naming conventions, comment requirements, no SELECT *;
- Security layer: row-level permissions, sensitive-field filtering, audit logging;
- Consistency layer: aligned metrics definitions, time-boundary handling, idempotency.
The research found that with each additional layer of structured constraints, the model’s overall probability of following all constraints doesn’t simply add up—it decays multiplicatively. Five layers each at 90% compliance can combine to only about 60% overall.
3. The Missing Validation Loop
Human developers run their SQL in a test environment, compare row counts, and spot-check results. But many teams using AI-generated SQL skip validation entirely and treat the output as final. AI output without assertion-based validation is, in essence, an untested half-finished product.
Practical Advice: Getting the Most Out of AI Coding Agents
1. Control Constraint Density and Deliver Requirements in Phases
Don’t pack every standard into a single conversation. A more effective approach is to break complex queries into steps: first have the model produce table relationships and a query skeleton, then layer in constraints incrementally (performance requirements, naming conventions, security filters), validating a small scope at each step. This aligns with the constraint decay pattern—the fewer constraints per task, the higher the compliance rate.
2. Replace Natural-Language Descriptions with Executable Standards
Rather than writing “follow team conventions” in your prompt, codify standards into machine-checkable form:
-- Example: assertion-based checks on AI output-- Constraint 1: must hit the partition fieldEXPLAIN SELECT ... WHERE dt = '${bizdate}'; -- check partition pruning in the execution plan-- Constraint 2: row-count reconciliationSELECT COUNT(*) FROM result_table; -- cross-check against the upstream table's row count
Combined with static checking scripts (e.g., banning SELECT *, enforcing field prefixes, detecting scans without partition filters), constraint enforcement shifts from “relying on the model’s self-discipline” to “machine-enforced backstops.”
3. Establish a Layered Human-AI Workflow
A recommended division of labor:
- AI handles: skeleton SQL generation, dialect conversion, boilerplate code, single-table query optimization suggestions;
- Humans handle: business-metric confirmation, complex JOIN logic review, permissions and compliance checks;
- Automation handles: standards checks, execution plan review, result reconciliation.
4. Evaluate Tools on Constraint Capacity, Not Leaderboard Rankings
When evaluating AI coding tools, instead of relying on public benchmark scores, build an evaluation set from your own team: pick 10 real historical query tasks, attach your complete set of standards, and see how the agent performs on “constrained rewriting.” Such an evaluation isn’t universal, but it best reflects real-world results.
Conclusion
Falling prices have dramatically lowered the barrier to using AI coding capabilities—an unambiguous benefit. But constraint decay research reminds us that there is a clear gap in agent capability between “simple tasks” and “constraint-dense tasks.” For data teams, the right posture is neither “hand everything to AI” nor “trust AI completely,” but redesigning the collaboration workflow: place AI where it performs well, and use engineering measures to constrain the parts where it doesn’t. Tools are getting cheaper, but using them well remains the human’s job.
