TablePad

Why my SQL agent writes several boring queries instead of one clever one

The design behind an AI agent that queries real databases: small visible steps, values passed only as bound parameters, one tool call per turn, and a server that validates every call. With the actual prompt.

7 min read

The standard design for "ask your database a question" goes: question in, one SQL query out, run it, show the result. It demos well. Then someone asks a real question, the model writes a 40-line query with three CTEs and a window function, and the answer is wrong. Nobody can tell where.

I build TablePad, a database client with a canvas where an AI agent answers questions against your data. I went the other way: the agent writes several small queries that a person can check by eye, linked by parameters, one at a time. This post is that design, with the real prompt and the rules the server enforces, so you can borrow what's useful.

I don't have a benchmark to wave around. What I can tell you is what this design changes about the failures, and that's the part I care about.

The principles, from the actual prompt

The system prompt opens with these lines, verbatim:

Several simple queries linked by parameters beat one clever query. Each step does one thing a person can check by eye.

Every query is a single read-only SELECT (or WITH … SELECT). No writes, no DDL, no locks, no multiple statements.

Values move between steps only as bound parameters: write :param_name in the SQL and declare it in inputs. Never paste values from earlier results into SQL text. A list input expands to a value list, so write IN (:order_ids).

Check facts with queries, not with explanations.

Each line exists because of a failure mode:

  • "Check by eye" turns one big opaque answer into a chain where each link is small enough to verify. If step 2 returns 7 orders and you expected about 7, you trust step 3 more.
  • "Bound parameters only" means a value from step 1 can never be re-typed wrong into step 2, and nothing from the data, such as a customer name that happens to contain a quote, ever becomes SQL text.
  • "Check facts with queries" stops the model from explaining that status 3 means delivered. It has to run SELECT DISTINCT status FROM orders LIMIT 20 and look.

Two shapes: trace and aggregate

Questions come in two kinds, and the agent has to decide which one it's answering before it plans.

Trace questions follow specific records: who bought the discontinued tent, and were their orders delivered? Each step runs on its own and hands values to the next one.

Three steps: find discontinued products, find orders that contain them using :product_ids, then customers and status for those orders using :order_ids
A trace block on the sample store. Each step's inputs are bound from the previous step's output, and each step is small enough to check.
-- step 1: discontinued
SELECT id, name, stock FROM products WHERE is_active = 0

-- step 2: tent_orders      :product_ids ← discontinued.id
SELECT DISTINCT order_id FROM order_items WHERE product_id IN (:product_ids)

-- step 3: buyers           :order_ids ← tent_orders.order_id
SELECT o.id AS order_id, c.name, c.country, o.status, o.ordered_at, o.shipped_at
FROM orders o JOIN customers c ON c.id = o.customer_id
WHERE o.id IN (:order_ids)
ORDER BY o.ordered_at

Aggregate questions are about totals and trends: revenue by channel per month. Following records one by one makes no sense there. In aggregate mode, each step is a CTE that later steps read by name (FROM paid_orders), and the app runs them combined as one WITH query. Intermediate steps only show a 50-row preview.

The switch between the two is automatic in one direction. A list parameter can carry at most 500 values. Past that, the app tells the model to re-plan in aggregate mode and let the database do the join, instead of shipping thousands of IDs back and forth.

One tool call per turn, and the app holds the state

The agent has exactly four tools:

Tool What it does
explore_query A tiny SELECT (at most 20 rows, no parameters) to look at real values before planning
set_plan Choose trace or aggregate, and list the steps with a one-line purpose each
write_step The code for one planned step: SQL or Python, its output name, its inputs, plus the check queries
finish Name the final step, pick a view, list the applied conditions in plain words

Parallel tool use is disabled, and every turn asks for exactly one call. The app runs it, shows the result to the person, and only then asks for the next one. The server keeps no conversation. Every turn sends the full state again: the request, the plan, each step's code and status, row counts, and a few masked sample rows. The model sees something like this:

### Step 2 · main · sql · output "tent_orders" · success
Purpose: Orders that contain them
Inputs: :product_ids <- discontinued.id (list)
```sql
SELECT DISTINCT order_id FROM order_items WHERE product_id IN (:product_ids)
```
Result: 7 rows; columns: order_id
Sample rows:
[24]
[42]
…

<task>
Write step 3 of the plan: "Customers and order status for those orders" (main).
Trace mode: take values from earlier steps through inputs. Call write_step.
Earlier results: discontinued(id, name, stock); tent_orders(order_id)
</task>

Stateless turns sound wasteful, but they buy two things. The person can edit any step between turns, and the next turn sees the edited code (marked "edited by the user") instead of a stale conversation. And retries are local: when a step fails, the task says "Rewrite this step only, keeping its place in the plan", with the database's error message. The prompt calls that message "ground truth".

The schema, the team's schema notes and examples from saved queries sit in a cached system block, so resending state each turn costs less than it sounds.

The server doesn't trust the tool call

Tool schemas are strict, but a schema can't know your database. Every call is checked before anything runs:

  • Is this tool allowed right now? A write_step during planning is refused with "Not now — call explore_query or set_plan for this turn."
  • Is the SQL a single read-only statement? (The guard is a tokenizer, not a regex.)
  • Is output_name a new snake_case name?
  • Does every input read from an earlier successful step, and does that step actually have the named column?
  • Is every :param in the SQL declared as an input?
  • In aggregate mode, are there no inputs at all? (Steps read each other as tables instead.)
  • Does a Python step assign to result?
  • Do the join-check keys exist in the schema?

A failed check goes back to the model as an error tool_result with a specific message, for example Step "tent_orders" has no column "product_id" (columns: order_id). The model gets two repair turns before the run stops. Because the message names the exact problem, the repair turn has something concrete to fix instead of a vague "invalid input".

Budgets, so it always ends

Agents that "keep trying" are expensive and confusing. Every number here is a constant in one file:

  • at most 6 explore queries before it has to plan
  • at most 8 steps in a plan
  • 3 attempts per step, then the step is handed to the person with its error
  • 30 turns per run, whatever happens
  • 15 s per query, 1,000 rows kept per step, and a cost estimate that pauses heavy queries for approval

What you get for the extra round trips

Answers you can audit. A wrong answer has a wrong step, and you can see which one. Each step also carries its own checks: a join fan-out count when it joins, and a contrast query when it comes back empty.

Conditions in plain words. finish has to list what it assumed: "soft-deleted orders excluded (deleted_at IS NULL)", "status 3 read as 'delivered'". Those lines are shown under the result. They're often the thing a reviewer actually needs to see.

Recipes, not transcripts. A finished block is a list of queries with parameters, so it can run again tomorrow without calling the model. Saving it as a reusable block asks the model one short, low-effort question: which literals in these queries are inputs a person would change, such as an order number or a date range, and which are fixed logic, such as a status code? The block becomes a form.

A schema that gets documented as a side effect. finish also returns schema note candidates: facts its explore queries verified, such as "orders.status: processing → shipped → delivered". They're saved only when a person approves them, and then every later run starts with them, so it explores less.

What it costs

  • Latency. A five-step trace is several model calls instead of one. For lookups that's fine. For a dashboard tile, you want the saved recipe, not the agent.
  • Over-splitting. Sometimes the model makes three steps out of what should be one join. That's mostly harmless, since each step is cheap, but it's noise.
  • Sample rows. The model sees a few rows from intermediate steps so it can write the next one. Sensitive columns are masked, and the final result's values are withheld. More on that in a separate post.

If you're building one

  1. Make the unit of work a step a person can check, not a query the model is proud of.
  2. Pass values between steps only as bound parameters. Never let data become SQL text.
  3. Separate trace from aggregate, and switch when the value lists get long.
  4. One tool call per turn, and keep the state in your app, not in the chat history, so people can edit it.
  5. Validate every tool call against the real schema and return specific errors. Give the model a couple of repair turns, then stop.
  6. Put hard budgets on everything, and hand the step to a person when they run out.
  7. Make the result a recipe that can run without the model.

None of this makes the model smarter. It makes its mistakes small, visible and local, which in my experience matters more.