Text-to-SQL vs Predefined Queries: Which Should Your AI Agent Use?
Use approved queries for the questions that matter in production, and text-to-SQL only as a read-only fallback for the questions you cannot predict.
Claix · November 2026. Related guides: Claix Retrieve vs open-source text-to-SQL, how to let an agent query Postgres safely, and the best database access layer for agents. Product: Claix Retrieve.
The two approaches in one minute
| Text-to-SQL | Predefined queries | |
|---|---|---|
| Who writes the SQL | The model, at question time | A person, ahead of time |
| What the agent decides | The whole query | Which query to use and its parameter values |
| Coverage | Anything the schema can answer | Only what has been written |
| Typical form | A raw database tool such as execute_sql | Named tools, stored procedures or API endpoints |
Neither is better in every case. They fail in different ways, which is why the choice matters.
How they compare
| Dimension | Text-to-SQL | Predefined queries |
|---|---|---|
| Flexibility | Very high | Limited to what exists |
| Safety | Depends on the guardrails around the model | High: the SQL was reviewed |
| Consistency | The same question can produce different SQL | Same question, same SQL |
| Accuracy on business terms | Varies; ambiguity such as active customer is a common failure | As accurate as the person who wrote the query |
| Setup effort | Low | Higher: one query per question type |
| Maintenance | Low, but results drift with schema and model changes | Every new question type needs a new query |
| Latency and cost | A model call to write SQL, sometimes several | Often just a lookup and a database call |
| Auditability | You review generated SQL after the fact | You review the SQL once, before it ships |
| Best for | Exploration, analysts, long-tail questions | Production, customer-facing and repeated questions |
Text-to-SQL: where it shines and where it breaks
Text-to-SQL is attractive because it needs almost no setup. Point the model at a schema and it can answer questions nobody planned for. That flexibility is also the source of its problems in production:
- Ambiguity. Business words such as active, churned or net revenue rarely map to a single column. The model picks an interpretation and states it confidently.
- Inconsistent output. Asking the same question twice can produce two different queries, and two different answers.
- Over-reading. A model asked for a customer's phone number may write SELECT * and pull columns you never meant to expose.
- Safety depends on everything around it. If the model can write any statement, the database role is the only brake. Read-only roles help but are not a full policy.
- Cost and latency. Every question needs a model call, and complex schemas need a lot of context.
- Expensive queries. A generated query can scan a large table and slow down production.
The usual mitigations are a dedicated read-only role with column-level grants, a parser that only allows a single SELECT on approved tables, row limits and statement timeouts, and a documented glossary so the model knows what your business terms mean. They reduce the risk without removing it.
Predefined queries: where they shine and where they break
With predefined queries, a person writes and reviews the SQL once. The agent supplies only parameter values, which are validated and bound, never concatenated into the statement.
import psycopg
ALLOWED_STATUSES = ('pending', 'shipped', 'cancelled')
def orders_by_status(conn: psycopg.Connection, status: str, limit: int = 20):
# The SQL is fixed and reviewed. The model only supplies validated values.
if status not in ALLOWED_STATUSES:
raise ValueError('unknown status')
if not 1 <= limit <= 100:
raise ValueError('limit must be between 1 and 100')
sql = (
'SELECT id, status, total FROM orders '
'WHERE status = %s ORDER BY placed_at DESC LIMIT %s'
)
return conn.execute(sql, (status, limit)).fetchall()The benefits are predictability, easy review and lower cost. The limits are coverage and upkeep:
- Coverage. A real agent receives questions nobody anticipated. Each one needs a new query or gets no answer.
- Maintenance. When a column is renamed, every query that uses it has to be found and fixed.
- The tool-selection problem. If every query is a separate tool, the agent has to choose among dozens of them, and their descriptions take up context. Selection gets worse as the catalogue grows.
You can build predefined queries by hand as stored procedures, API endpoints or MCP tools. Open-source projects such as Google's MCP Toolbox for Databases let you define custom tools in a YAML file. Writing a handful of queries by hand is a good fit when your questions are few and stable.
The hybrid pattern most production agents need
Predefined queries are safe but narrow, and text-to-SQL is broad but risky. A hybrid uses each where it is strongest:
Question in natural language
-> does an approved query match?
|- yes -> fill validated parameters -> run the approved SQL
|- no -> generate one read-only query inside strict limits -> run it
-> log the question, the path taken and the result
-> questions that repeat get reviewed and promoted into approved queriesThree details make the hybrid work:
- A single entry point for the agent. The agent asks in natural language and the system decides whether an approved query applies. The agent does not need to know the catalogue.
- A safe fallback. When no approved query matches, generation happens inside a read-only role, an allowlist of tables and columns, a single-SELECT parser and row and time limits.
- A feedback loop. Questions that keep arriving through the fallback are the best candidates for new approved queries, so coverage grows from real usage instead of guesswork.
The main new risk is picking the wrong approved query with too much confidence. Reduce it with a confidence threshold that falls back to generation, negative examples in your tests, resolving things like last month in code instead of leaving them to the model, and a trace that shows which query was used.
How Claix Retrieve implements this
Claix Retrieve connects to your SQL database (PostgreSQL, MySQL, MariaDB, Supabase) through a read-only role. You decide which tables and columns each agent can use through routes, and your agent asks questions in plain language over REST, MCP or A2A. Routes come in two kinds:
| Route type | What the model does | Where the SQL comes from |
|---|---|---|
| Fixed | Selects an approved, parameterised template and fills validated variables. It never writes SQL | A person approved the query |
| Open | Writes one read-only SELECT inside the route's allowlist and rules | A deterministic check rejects anything else before it runs |
Results come back as typed answers (string, int, boolean, date, json, arrays) instead of raw rows, and each query is traced, so you can see which path an answer took. The agent has one tool to call, not one per query.
This is one way to get the hybrid. You can also build it yourself with stored procedures, a thin API and a read-only fallback. The trade-off is that you own the matching, the validation, the fallback limits and the upkeep.
Which should you choose?
| Your situation | Recommended approach |
|---|---|
| Exploring a database while building | Text-to-SQL on a development copy |
| A few stable questions that must be exact | Predefined queries |
| An agent inside a product that reads customer data | Hybrid, with approved queries for the common questions |
| Many unpredictable questions from non-technical users | Hybrid with a strict, read-only fallback |
| Strict compliance or audit requirements | Predefined queries, with a reviewed and logged fallback or none at all |
| Any write operation | Never free-form SQL: approved actions plus a check before execution |
How to know it is working
Measure the setup instead of trusting it:
- Share of questions served by approved queries. It should grow over time.
- Wrong-match rate. How often the wrong approved query was selected, checked on a sample.
- Accuracy on a test set of real questions with known answers, run after every schema or model change.
- Latency and cost per answer for each path.
- Blocked attempts, meaning queries the safety checks rejected.
Frequently asked questions
- Should an AI agent write SQL or use predefined queries?
- For production use, prefer predefined (approved, parameterised) queries for the questions you can anticipate, and use generated SQL only as a controlled, read-only fallback. For exploration on a development copy, text-to-SQL is fine.
- Is text-to-SQL safe for production?
- It can be made safer with a read-only role, column-level grants, a parser that only allows a single SELECT on approved tables, row limits and timeouts, but those controls reduce risk rather than remove it. An approved query removes the model from the SQL entirely.
- What are predefined queries for AI agents?
- They are SQL statements written and reviewed by a person in advance, exposed as stored procedures, API endpoints, MCP tools or templates. The agent chooses one and supplies parameter values that are validated and bound.
- Why not give the agent one tool per predefined query?
- It works for a handful of queries. With dozens, the agent has to choose among many tools and their descriptions use up context, so selection quality drops. A single natural-language entry point that routes to approved queries avoids that.
- What is a hybrid approach?
- It uses approved queries when one matches the question and a restricted, read-only generation path when none does. Questions that repeat are promoted into approved queries.
- Does text-to-SQL give consistent answers?
- Not necessarily. The same question can produce different SQL on different runs, especially when business terms are ambiguous. Approved queries return the same SQL for the same question type.
- Does Claix generate SQL?
- In open routes, the model writes one read-only SELECT inside the route's allowlist, and a deterministic check rejects anything outside it before execution. In fixed routes, the model only selects an approved template and fills validated variables.
- Can the agent write data with either approach?
- Writes should not go through free-form SQL in either case. Use approved actions, and check every INSERT, UPDATE or DELETE with a deterministic checker before your own code runs it.
- How do I add predefined queries without rewriting my agent?
- Put a single natural-language entry point in front of them, so the agent keeps asking questions in plain language and the system matches them to approved queries.
Conclusion
The choice is not text-to-SQL versus predefined queries; it is how much of the SQL you are willing to leave to a model. Approved queries give you predictability and safety on the questions that matter, generation gives you reach on the ones you did not foresee, and a hybrid with a feedback loop lets coverage grow from real usage. Claix Retrieve offers fixed and open routes behind a single natural-language tool, over a read-only role, with typed answers and traces. Try Claix Retrieve free: 30 successful calls per month.
You might also like…
Comparison · Retrieve
Claix Retrieve vs Open-Source Text-to-SQL Frameworks: The Safer Way to Give AI Agents Database Access
Security · Agents
How to let an AI agent query your Postgres database safely
Architecture · Agents
Best database access layers for AI agents (2026 guide)
Guides · Supabase
How to Give an AI Agent Safe Access to Your Supabase Database with Claix