Skip to content

Agentic AI & Orchestration

AI-Written SQL Needs More Than Read-Only Access

A read-only agent can still saturate a database with scans, joins, and spills. Put a replica, SQL gateway, plan check, and execution budget between the model and production data.

Mara QuinteroAgents & Orchestration Writer

November 19, 2026 · 8 min read

A laptop displaying a SQL execution plan beside a database monitoring screen showing a constrained query queue.
A laptop displaying a SQL execution plan beside a database monitoring screen showing a constrained query queue.

Use one recurring request as the design target: every Monday, an operations manager asks an agent for revenue by region from the previous week. The agent translates that request into SQL, checks the result, and writes a short explanation.

The dangerous version gives the model read-only credentials to the production database. One plausible query joins orders to customers, applies a date function to every order timestamp, groups the result, and sorts it. It cannot update a row, but it can scan a large table, consume memory, spill temporary data to disk, and compete with customer-facing queries.

That Monday revenue query should pass through several controls before it sees one sales figure. The agent first receives a limited schema description. A gateway checks the SQL structure, asks the database for an execution plan, compares that plan with a workload budget, and only then submits the query to an isolated replica.

Read-only blocks writes, not expensive work

A read-only account prevents common mutations such as `INSERT`, `UPDATE`, and `DELETE`. It does not make arbitrary `SELECT` statements cheap.

Large joins and unbounded aggregations can consume the same CPU, memory, storage bandwidth, and worker capacity needed by operational traffic. A result limit offers weak protection because the database may still scan and sort millions of rows before returning the first hundred. Depending on the engine and permissions, a supposedly read-only user may also create temporary objects, invoke expensive functions, or call stored procedures with broader privileges.

Keep the permission boundary. Give the agent its own database role with access only to approved views or tables, no ownership rights, no schema creation, and no ability to bypass row-level security, which restricts which records a role may see. Remove unnecessary function permissions as well. The role remains useful even though it is only one layer.

Keep the agent off the operational replica

Send agent traffic to a read replica, a continuously updated copy of the primary database that accepts queries without handling application writes. Better still, use a replica or warehouse endpoint reserved for analytical and agent workloads rather than the standby intended to take over during an outage.

That distinction matters. A long query on a standby can conflict with replication cleanup, increase replica lag, or retain old data versions longer than expected. If the agent shares a failover target with production, its read-only query can weaken the system meant to protect production.

The isolated endpoint needs a separate connection pool and workload policy. It should be safe to pause or shed agent traffic without interrupting dashboards, application requests, or disaster recovery. Freshness becomes the tradeoff: the Monday revenue answer may lag behind the primary, so the tool should return the replica timestamp or known lag alongside the result rather than presenting the numbers as current.

Put a

SQL gateway between the model and credentials

The model should call a narrow tool such as `preview_query` or `execute_approved_query`. That tool owns the credential; the model never sees a password or connection string.

When the Monday request arrives, the gateway parses the generated SQL into an abstract syntax tree, a structured representation of the statement rather than a string of words. String checks alone are brittle because comments, nested expressions, alternate syntax, and multiple statements can hide behavior that a keyword filter misses.

The gateway should accept one statement and verify that its top-level operation is a read. It then checks every referenced schema, table, view, function, and operator against an allowlist. Block system catalogs unless they are required, reject unknown functions, and refuse multi-statement input. Common table expressions need inspection too; the presence of `WITH` does not prove that the enclosed operation is harmless across database engines.

For a small workflow, the strongest allowlist is a set of curated analytics views. The agent might query `weekly_orders` and `customer_regions` while remaining unable to inspect payment details or free-form support notes. A broader assistant can allow selected columns from base tables, but that increases policy complexity and the chance that sensitive fields appear in intermediate or returned data.

Parameterized query templates are stricter still. They let the model choose a date range, region, grouping, or approved measure without inventing the full statement. They cover fewer questions, but they are often the right starting point for a repeated task such as the Monday revenue report.

Preview the plan before releasing data

After structural validation, the gateway requests an execution plan without running the query. In PostgreSQL terms, that means `EXPLAIN` rather than `EXPLAIN ANALYZE`; the latter executes the statement and defeats the purpose of a preflight check.

A plan describes how the database expects to obtain the result, including scans, joins, sorts, and estimated row counts. The gateway can reject the Monday query if it predicts a full scan of a protected large table, a cross join, an unusually large intermediate result, or work above the budget established for that replica. Cloud warehouses may expose estimated bytes scanned, which can become the clearest cost gate.

Do not copy a generic cost threshold from another database. Planner cost units are engine-specific, table statistics can become stale, and estimates may be wrong when data is skewed or predicates are correlated. Build the initial budget from known acceptable queries on the same endpoint, then keep a conservative margin below the point where interactive workloads suffer.

A rejected plan should return a small, sanitized reason to the agent: the date predicate prevents indexed access, the join lacks an approved key, or the estimated scan exceeds policy. Let the model revise once. Repeated automatic retries can turn one bad query into a queue of slightly different bad queries, so the gateway should stop after a limited attempt and hand the request to a person or a maintained report.

Enforce the budget again during execution

A plan preview predicts work. Runtime controls stop work that exceeds the prediction.

Start each accepted query in a read-only transaction and apply a statement timeout at the database or session level. Add a concurrency cap for the agent pool, plus engine-specific limits on memory, temporary storage, rows returned, or bytes scanned where those controls exist. The connection pool should queue only a small amount of work; once that queue is full, reject new requests rather than transferring the overload from the database to the gateway.

Cancellation must reach the database session. Abandoning an application request while the SQL continues in the background saves no capacity. After a timeout, verify that the database canceled the statement and discard or reset the connection before reuse.

Treat timeout as a terminal result, not an invitation to retry with a longer allowance. The fallback for the Monday report is an approved summary table, a cached prior run labeled with its timestamp, or human review of a revised query. Which fallback fits depends on whether freshness or availability matters more for that workflow.

Limit what the agent can inspect and return

Schema discovery should be curated rather than open-ended. Give the agent table descriptions, approved relationships, data types, and examples that do not contain live customer records. This reduces exploratory queries against system catalogs and makes incorrect joins less likely.

Once execution is approved, cap the output independently of database work. Prefer aggregated results for business questions, reject `SELECT *`, and restrict columns that can leave the gateway. Masking and row-level policies still apply on the replica because copied production data remains production data for access-control purposes.

Log the prompt or structured request, generated SQL, policy decision, plan summary, execution identity, timing, cancellation status, and returned column names. Avoid putting unrestricted result rows into observability systems, where sensitive data can acquire a second retention policy and a wider audience.

For the Monday revenue query, the final trace should show a bounded request against approved views, a plan under the local budget, one execution on the analytics replica, and a timestamped aggregate result. If any link is missing, the agent should not improvise around it.

Questions people ask

Are read-only database credentials safe for an AI agent?

They are necessary but insufficient. Read-only credentials block common data changes, while expensive scans, joins, sorts, functions, and temporary work can still disrupt a shared database. Use a dedicated role behind a gateway, then enforce workload limits on an isolated query endpoint.

Should the agent query a replica or a data warehouse?

Use the endpoint that can absorb analytical work without competing with application traffic. A dedicated replica offers familiar SQL and relatively fresh data, while a warehouse may provide stronger scan accounting and isolation. In either case, expose data freshness because replicated or loaded data can lag behind the primary system.

Can a query plan guarantee that SQL is cheap?

No. A plan is an estimate based on statistics and engine assumptions, so skewed data or stale statistics can produce a bad prediction. It is still useful as a rejection gate, provided runtime timeouts, concurrency controls, and cancellation remain in place.

Should the agent automatically rewrite a rejected query?

Allow a tightly limited revision when the gateway can provide a safe reason, such as an unbounded date range or disallowed table. Do not let the model retry indefinitely or raise its own limits. After the retry budget is exhausted, route the request to a maintained report or human review.

ShareFacebook
ai agentstool use and function callingai at workai agentssql safetydatabase orchestrationquery governance

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.

Read next

Calendar and OAuth permission screens open beside an agent activity log on a laptop.

Agentic AI & Orchestration

Your AI Agent’s Real Boss Is Its OAuth Token

A calendar assistant may be told to touch one meeting, while its token permits access to every event. Scope the credential, not just the prompt.

Mara Quintero · 7 min read

A contact-center screen showing a live call, transfer status, transcript and verification record beside a headset.

Agentic AI & Orchestration

Voice Agents Need a Warm Transfer, Not a Callback

A useful voice agent carries the live call, identity evidence, transcript and unfinished request to a human. That requires explicit transfer state, not another model prompt.

Mara Quintero · 8 min read

Support ticket beside an order-system panel showing a failed refund and a blocked closure state.

Agentic AI & Orchestration

A Support Agent Should Have to Prove a Case Is Closed

A support agent can write a convincing resolution while the refund, replacement, or account change remains unfinished. A closure gate checks the record instead of trusting that summary.

Mara Quintero · 7 min read