Let the Database Agent See Views, Not Your Production Tables
A natural-language database agent can handle recurring analysis without arbitrary SQL access. The workable setup combines narrow views, enforced query budgets and a separate path for changes.
August 9, 2026 · 8 min read

Consider a Monday refund review. A support operations lead asks an agent which products had an unusual rise in refunds last week, which reason codes contributed, and whether the pattern continued into the weekend. The agent turns that request into SQL, runs several queries and writes a short explanation with links to the underlying aggregates.
That is a practical agent job. It has a defined question, a bounded date range and an output a person can check. It also becomes dangerous if the model receives a general production credential, because read-only SQL can still expose customer records, scan large tables, hold locks in some database configurations or consume enough capacity to slow the application.
The safer design starts before the prompt. Build a small analytical surface for the Monday refund review, give the agent its own identity, and place a query service between the model and the database. The model may propose SQL. The service decides whether that SQL is allowed to run.
Start with the questions, then design the views
A database view is a saved query presented like a table. For the refund review, one view might expose daily order and refund counts by product, while another groups refund events by a controlled reason category. Neither needs a customer name, email address, shipping address, payment reference or free-text support note.
A useful first view could contain `order_date`, `product_id`, `product_name`, `orders`, `refunds` and `refund_rate`. The reason view might contain the date, product identifier, approved reason group and event count. The agent can join them through `product_id`, compare periods and rank changes without touching the raw orders or customer tables.
The database role assigned to the agent should receive `SELECT` permission only on those views. Revoke access to the underlying schemas rather than relying on instructions such as “never query customer data,” because model instructions are behavioral guidance, while database permissions are enforced after the model has produced a query. Depending on the database, view definitions and ownership settings also need review so that the view does not accidentally inherit broader access or expose restricted columns through a convenience wildcard.
Views encode policy, but they also encode meaning. If the business defines refund rate as refunded units divided by fulfilled units, calculate or document that definition in the view rather than asking the agent to infer it from several status fields. This reduces flexibility. It also prevents the Monday report from quietly changing its denominator because the model chose a plausible column.
Keep the catalog small enough to describe clearly. Each exposed field needs a plain-language description, its unit, its update cadence and any exclusions. The agent should know, for example, whether dates use UTC, whether canceled orders are absent and whether the current day remains incomplete. Without that context, valid SQL can still produce a wrong answer.
Put enforcement between the model and SQL
The model should call a narrow tool such as `run_analysis_query`, not open a general database connection. That tool accepts proposed SQL and passes it to a service that parses the statement, checks referenced objects against an allowlist and rejects anything except a single read query. String matching is too brittle for this job; a SQL parser builds a structured representation of the statement, which makes nested queries and indirect object references easier to inspect.
After validation, the service runs the query with the agent’s restricted database role. It applies a server-side statement timeout, which cancels work that exceeds the permitted duration, and a result limit measured in rows or response size. The service should attach the final SQL, runtime status, returned row count and any truncation flag to the agent run log.
Those controls must sit outside the prompt. Asking the model to add `LIMIT` is useful for reducing mistakes, but the model can omit it, place it at the wrong level or generate an aggregation that returns few rows only after scanning a large table. The query service should impose its own maximum, while the database or workload manager enforces the execution deadline.
A row cap and a timeout solve different problems. The cap prevents a query from returning an export-sized result or filling the model’s context window, which is the amount of text and data it can consider in one run. The timeout limits database work, although it remains a coarse control because an expensive query can consume substantial resources before cancellation. If the production system is sensitive to analytical load, point the views at a read replica or warehouse and accept that the agent’s answers will lag behind the application’s latest writes.
The Monday refund review shows the tradeoff. A query grouped by product and day should fit comfortably inside a narrow result set, but an unrestricted request for every refund event would be rejected or truncated. If the support lead needs case-level inspection, the agent can return approved record identifiers that open in an existing internal tool, where normal permissions still apply.
Make failure visible instead of letting the agent improvise
Suppose the agent asks for a full year of daily product data while investigating last week. The query hits its deadline. A bounded retry policy may let the agent narrow the dates or query a pre-aggregated view once, but it should not keep rewriting the request until something runs. Repeated attempts add load and can make a long-running workflow harder to audit.
The final answer should distinguish a database result from a model interpretation. For the refund review, the agent can show the comparison periods, the number of products evaluated and whether the query returned a complete set. If a row cap cut off the result, the agent should not describe the visible rows as the global top products unless the database performed the ordering before the enforced cap.
Some questions should fail. If the operations lead asks whether refund growth correlates with customer age and no approved view contains age bands, the agent should report that the available data cannot answer the request. Granting temporary access during the run defeats the boundary and makes later investigation difficult.
Test the setup with questions that produce empty periods, duplicated joins, incomplete current-day data and dimensions absent from the catalog. Save the expected SQL shape and answer properties rather than demanding identical prose. The important checks are whether the agent stayed within approved objects, disclosed truncation, respected the requested period and stopped after a canceled query.
Send writes through another workflow
The refund review may end with a request to disable a product, change a return rule or annotate an internal record. None of those actions belongs in the analysis connection.
Give the agent a separate tool that creates a structured change request. It can include the proposed action, target identifier, evidence query, requested parameters and the person who asked, but it cannot issue `UPDATE`, `DELETE` or data-definition commands. An authorized person reviews the request, and a deterministic service, meaning code with predefined behavior rather than model-generated SQL, executes an approved operation through a parameterized command.
That separation adds delay. It also creates a stable place for authorization checks, conflict handling and an audit record, while keeping the model away from arbitrary writes. For repetitive low-risk changes, teams can later approve a narrow action type in advance, such as adding a product to a review queue, without broadening the agent’s database role.
The handoff needs an idempotency key, a unique value that prevents the same approved request from being applied twice. This matters when an agent retries after a network error and cannot tell whether the first call succeeded. The execution service should return a durable status that the agent can report rather than guessing from a timeout.
Which jobs fit inside the boundary
The strongest candidates resemble the Monday refund review: recurring comparisons over known measures, exception finding across approved dimensions, operational summaries and follow-up queries that remain within a documented analytical model. The agent saves time by translating ordinary language into filters, joins and grouped calculations, then carrying context from one query to the next.
Open-ended data discovery fits less well. An analyst who needs to inspect unfamiliar schemas, build new metrics or reconcile raw events will find the view boundary restrictive. A conventional business intelligence tool may also be cheaper and easier to govern when users mostly need fixed dashboards with a few filters; the agent earns its extra model and orchestration cost when the questions vary enough to require query planning and explanation.
Views need maintenance as schemas and business definitions change. Query logs reveal which questions repeatedly fail, but a failed request should become a reviewed proposal for a new field or aggregate, not an automatic permission expansion. For the Monday report, adding fulfillment channel might be reasonable after data owners confirm its definition and sensitivity. Adding free-text complaint notes would require a different risk review and probably a different tool.
Questions people ask
Is read-only database access safe for an AI agent?
Read-only access prevents direct updates, but it does not prevent sensitive-data exposure or expensive queries. Restrict the agent to approved views, enforce execution limits through a query service and isolate analytical work from the production workload when application performance cannot tolerate unpredictable scans.
Should the agent query a production database or a warehouse?
Use a warehouse or read replica when production latency matters more than immediate freshness. Direct production reads may suit a tightly indexed operational lookup, but an analytical agent generates less predictable SQL, so teams should assume that some valid queries will still be inefficient.
What happens when the row limit cuts off an answer?
The query service should mark the result as truncated and return that status to the agent. The agent can narrow the period, aggregate inside the database or ask the user to refine the request, but it should not present the partial rows as a complete ranking.
Can the agent ever make database changes automatically?
It can trigger predefined actions through a separate service after the organization sets an approval policy for that action type. The agent should submit structured parameters rather than generated write SQL, and the service should check authorization, prevent duplicate execution and record the outcome.
One story a day
The story of the day, in your inbox
One real story about AI each morning — no hype, no alarm, just company for the road.



