AI-Ready Data Jwkweon

Why Does a Text-to-SQL Agent Write Wrong Queries? Check Its Data Context

An orders table on the left and a joined result on the right where one order row appears twice

A data team connects a SQL agent to an order database, and the query the agent generates runs without an error. The total it returns is still wrong.

Data context for a text-to-SQL agent is the information around a database schema that the agent needs to write the right query: what each column means and in which unit, how tables relate and what one row represents, and how the business defines the metric being asked for.

Adapted from When a SQL Agent Is Wrong, Check Its Data Context by Jwkweon of CUBIG on the CUBIG Tech Blog (November 2026). Jwkweon’s order and payment system is a fictional example.

CUBIG counts this information as part of the data a text-to-SQL agent works from, not as a prompt detail. CUBIG defines AI-ready data as data prepared for a specific AI task, with results checked, that a team can recheck where needed when conditions change. The same orders table can be ready for one business question and missing what another question needs.

Enterprise-scale tasks are harder still. In Spider 2.0, a text-to-SQL benchmark built from 632 enterprise workflow problems (Lei et al., ICLR 2025), the authors report that their code agent framework based on o1-preview “successfully solves only 21.3% of the tasks, compared with 91.2% on Spider 1.0 and 73.0% on BIRD”. The benchmark’s databases often contain over 1,000 columns, and its tasks often require searching database metadata and dialect documentation, among other steps.

Key takeaways

  • A query that runs without an error can still answer the wrong question.
  • A schema lists tables and types; it does not say what a value means, what one row represents or how the business defines a metric.
  • The definitions only help if they reach the agent through the information path it uses.
  • Before changing the model or the prompt, read a wrong query for clues about which context may have been missing.

Why can a text-to-SQL query run and still be wrong?

Consider the fictional order and payment system. The orders table holds one row per order. The payments table holds one row per payment, and a customer can pay an order in several installments. A user asks for the total order amount across orders that have a payment record, and the agent writes:

SELECT SUM(o.order_amount)
FROM orders AS o
JOIN payments AS p
  ON o.order_id = p.order_id;

Suppose one order has an amount of 100,000, paid in two installments of 60,000 and 40,000. The join returns that order twice, so the sum is 200,000 instead of 100,000. The figures are illustrative, taken from the fictional example in Jwkweon’s 2026 post.

The agent can make this mistake while knowing every table name and column type. Checking for a payment with EXISTS, or joining against distinct order IDs from payments, gives the right total. Choosing either fix starts with knowing that orders and payments have a one-to-many relationship and which unit the query aggregates.

What does a database schema leave out?

A database schema describes tables, columns, types and declared constraints. Business questions often need more. An amount column might store currency units or the smallest currency denomination, before or after discounts, with or without tax and shipping. A numeric status column does not say whether status = 3 means payment completed or delivery completed, and a NULL might mean a value was not collected, does not apply or has not arrived yet, as Jwkweon’s 2026 post points out.

Useful column documentation answers four questions:

  • What does the value represent, and in which unit?
  • When is it recorded or updated?
  • What do the codes and missing values mean?
  • Which conditions matter when calculating or comparing it?

A description such as “Stores the order amount” adds little to the column name; “Item amount after discounts, excluding shipping and tax” gives the query writer something to work with. The definition also has to reach the agent. A correct explanation in a wiki cannot guide a query if the agent only receives a list of column names. Related entries: data context and business glossary.

Comparison of what a database schema gives a SQL agent, tables, types and keys, and what data context adds: value meanings and units, grain and cardinality, and metric definitions

What is grain, and why does a SQL agent need it?

Grain is the unit one row represents. An orders table may hold one row per order, an order-items table one row per item and a shipments table several rows for one order, so joining them changes how many rows represent the same order. For the fictional system, three short lines establish the distinction:

  • orders: one row represents one order, and the order amount is recorded at order level.
  • order_items: one row represents one item within an order, and an order can have several items.
  • payments: one row represents one payment, and an order can have several payments.

Without relationship information, the agent may infer connections from names or sample rows. Matching names do not guarantee matching identifier systems, and a small sample with no duplicate values does not establish uniqueness across the database. Documented keys, uniqueness conditions and relationship cardinality can reduce that guesswork.

Where the database does not enforce constraints, someone also has to check that the documented relationships still hold in the actual data. Incorrect metadata can guide an agent toward an incorrect query, so the descriptions around a database need the same maintenance as the records.

Who defines the metric a text-to-SQL agent calculates?

A request for “this month’s order value” can mean orders created this month or payments completed this month, with or without cancelled orders, partial refunds and a specific time zone. Several technically valid queries can answer different versions of the same question, and the business, not the agent, decides which version counts.

For an engineer, the question is where those definitions live and how the agent receives them. A team can expose an established metric through a maintained view or calculation, and state the assumptions behind an exploratory metric. Separate copies create work: if a dashboard uses the current definition while an agent prompt holds an older one, a model upgrade leaves the discrepancy in place. Related entry: semantic layer.

Databricks makes a related point about agents that run outside the systems governing the data. Its July 2026 post on data-native AI agents notes that “Metric definitions, business glossary, and domain groupings live in your governance layer” and that “an external agent rebuilds them from column names, or guesses.” The practical check is whether access to the data also delivers the information needed to interpret it.

How much context should a SQL agent receive?

Putting every column description, relationship and business rule into the prompt gets harder to maintain as the number of tables and documents grows. Unrelated schemas add input and increase the number of candidates the agent must tell apart, so having enough documentation and selecting the relevant part are separate engineering problems.

Anthropic’s September 2025 guide to context engineering for AI agents describes “just in time” agents that “maintain lightweight identifiers (file paths, stored queries, web links, etc.)” and “use these references to dynamically load data into context at runtime using tools.” A SQL agent can follow a similar pattern: identify the relevant data area and tables, inspect their columns and relationships, then retrieve the definitions and value examples the question needs.

The data those tools return matters. A response with the relevant column meanings, units and relationships can serve a question better than hundreds of unexplained column names. Heavy compression can also drop an exception the query needs, so a shorter response is not automatically a better one.

CUBIG Shorts

Is that wrong AI answer really a data problem?

A short clip from CUBIG on tracing one wrong AI answer before redesigning the agent.

▶  Watch on YouTubeSubscribe

How do you read a failed text-to-SQL query?

An incorrect query is also evidence about what the agent may have been missing:

  • If the agent selects the wrong table, inspect the table descriptions and the discovery path.
  • If an aggregate grows after a join, check whether grain and cardinality were available.
  • If cancelled orders appear in a metric, inspect the status definitions and business rules supplied at the time.

When the relevant information was available and correct but the agent failed to apply it, the next investigation may concern model capability, instructions or tool use. Data preparation will not resolve every failure, and separating the two kinds of failure helps locate the change worth making. Repeated schema discovery, extra queries to establish what a field means and calculations based on unresolved definitions also consume tool calls, tokens and time.

Three symptoms of a wrong SQL query and the context to check for each: wrong table, a total that grows after a join, and cancelled orders counted in a metric

Where does CUBIG fit?

Syntitan, CUBIG’s AI-ready data platform, checks a dataset against a specific task. Syntitan’s Ready for Raw Data check reviews a dataset’s condition from six perspectives: usability, integrity, context, consistency, reproducibility and traceability. Of the six, context is closest to this article: it looks at whether field meanings, units, business terms and relationships are documented. Syntitan keeps the original dataset intact, starts each Use Case Project from a copy and records preparation and verification results as Versions.

Syntitan does not write a company’s metric definitions or decide what “order value” means; the people who own the metric make that call. In the order example, more order rows would not have explained the mistake. The missing information was what a row represented and how the join changed it.

When a SQL agent gets an answer wrong, inspect the context that reached it along with the query itself. See how Syntitan keeps the original dataset intact and records each prepared Version.

Explore Syntitan, CUBIG's AI-Ready Data Platform

FAQ

What is data context for a text-to-SQL agent?

Data context is the information around a schema that an agent needs to write the right query: column meanings and units, table relationships and grain, and the business definition of the metric being asked for.

Why does a SQL agent return a wrong total when the query runs?

One cause is a one-to-many join that repeats rows, such as joining orders to several payments and then summing the order amount. Knowing the grain of each table helps avoid it.

Should I put the whole schema documentation into the prompt?

Not necessarily. Unrelated schemas add input and more candidates to choose from. Let the agent find the relevant tables first, then load the definitions it needs.

Is a wrong SQL answer always a data problem?

No. If the right information reached the agent and it still failed, look at model capability, instructions or tool use. Reading the failed query helps show which case applies.