Imagine building an AI assistant that helps your support team investigate customer orders.

A support agent asks:

Show me the last five orders for customer 142.

Your AI agent generates SQL, executes it against PostgreSQL, and returns the results.

Everything works.

Then someone asks:

Find all customers who haven't placed an order this year and delete their accounts.

The AI generates another query. This time, it's a DELETE.

If your agent has unrestricted database access, the difference between reading five orders and deleting thousands of customers might be nothing more than the SQL it generates.

That's a serious architectural problem.

I've worked on AI agents for database engineering and other tool-calling workflows. One principle I keep coming back to is that an LLM should never be the final authority on what an application is allowed to do.

Let's look at how to design safer database tools without making AI agents unnecessarily complicated.

1. Why Giving an Agent a Database Connection Is Risky

A common approach to building a SQL agent looks like this:

User Question | v LLM | v Generate SQL | v Execute Against Database | v Return Results 

This is attractive because it's flexible.

The agent can answer questions developers didn't anticipate when designing the application.

But the flexibility introduces several risks.

An agent might generate an expensive query, access another customer's data, expose sensitive columns, or execute a destructive statement.

And the problem isn't limited to malicious users.

A perfectly reasonable request can produce incorrect SQL because the model misunderstands the schema or business requirements.

Prompt injection makes things worse.

An attacker could place malicious instructions inside a support ticket, document, or other content the agent retrieves. If the model treats that content as an instruction, it might attempt an unauthorized tool call.

OWASP identifies this broader problem as Excessive Agency: giving an LLM more functionality, permissions, or autonomy than its task requires.

Reference: OWASP Excessive Agency.

2. Start With the Principle of Least Privilege

The first defense shouldn't be a better prompt.

It should be a database account that cannot perform dangerous operations.

If the assistant only needs to read order information, its database credentials shouldn't be able to update or delete orders.

For example, a database administrator could provision a dedicated role:

CREATE ROLE ai_reader LOGIN PASSWORD 'replace-with-secret'; GRANT CONNECT ON DATABASE appdb TO ai_reader; GRANT USAGE ON SCHEMA public TO ai_reader; GRANT SELECT ON orders TO ai_reader; 

This is an illustrative setup. Use a secrets manager to provision credentials, and grant only the tables or views required by the application.

Don't give the agent the same credentials used by your main backend.

Also, avoid granting broad schema access when the task only requires a few specific fields.

For an order-support assistant, exposing a curated view is often preferable:

CREATE VIEW support_order_summary AS SELECT id, customer_id, status, created_at FROM orders; 

Grant access to this view rather than the underlying table.

This narrows the data available to the agent.

However, a view is only one part of the security model. Its ownership and security configuration matter, particularly when combined with PostgreSQL row-level security.

3. Prefer Purpose-Built Tools Over Arbitrary SQL

Here's the design choice I'd make for most customer-facing AI agents.

Instead of exposing this:

execute_sql(query: str) 

Expose specific capabilities:

get_recent_orders(customer_id: int, limit: int) get_order_status(order_id: int) count_failed_orders(start_date: str, end_date: str) 

Now the LLM chooses an operation and provides parameters.

It doesn't invent the SQL.

The application controls the query structure.

For example, using Python and psycopg:

def get_recent_orders(conn, customer_id: int, limit: int = 5): if not 1 <= limit <= 20: raise ValueError("Invalid limit") with conn.cursor() as cur: cur.execute( """ SELECT id, status, created_at FROM support_order_summary WHERE customer_id = %s ORDER BY created_at DESC, id DESC LIMIT %s """, (customer_id, limit), ) return cur.fetchall() 

This is much easier to inspect and test than arbitrary model-generated SQL.

Parameterized queries also separate values from SQL syntax, reducing SQL injection risk.

But there's an important detail.

Valid SQL parameters don't automatically mean the user is authorized to access those records.

The backend must verify whether the caller has permission to view the requested customer's information.

The model shouldn't be able to bypass that check simply by changing customer_id.

4. Enforce Tenant Isolation Outside the Model

For a multi-tenant SaaS application, this is especially important.

Imagine two organizations:

Organization A Customer 142 Customer 143 Organization B Customer 501 Customer 502 

A user belonging to Organization A should not be able to retrieve Organization B's records.

You could put this in the system prompt:

Only retrieve records belonging to the current user. 

But the prompt isn't a security boundary.

The application should derive the tenant identity from the authenticated session, not from a parameter supplied by the LLM.

A safer query might look like:

SELECT id, status, created_at FROM orders WHERE organization_id = $1 AND customer_id = $2 ORDER BY created_at DESC, id DESC LIMIT 20; 

Here, $1 comes from trusted authentication context.

The agent can request a customer ID, but it cannot choose which organization it belongs to.

For stronger database-level isolation, PostgreSQL supports Row-Level Security (RLS).

RLS lets database policies control which rows a database role can access.

This can provide defense in depth when application queries are incorrect.

However, RLS needs careful configuration. Table owners and roles with special privileges may bypass policies, and policies relying on session variables require a trusted mechanism for setting those values.

Reference: PostgreSQL Row Security Policies.

5. Protect the Database From Expensive Queries

Read-only access doesn't mean risk-free access.

An AI-generated query might join several large tables, scan millions of rows, or return an excessive amount of data.

It may not modify anything, but it can still overload the database.

PostgreSQL provides useful controls such as statement_timeout.

For example:

ALTER ROLE ai_reader SET statement_timeout = '3s'; 

This sets a default statement timeout for sessions using that role.

The three-second value is illustrative. Choose it based on expected workloads and database performance.

You can also configure read-only transactions:

ALTER ROLE ai_reader SET default_transaction_read_only = on; 

This provides another safeguard, but it doesn't replace restrictive database privileges.

A role with unnecessary write permissions remains an avoidable risk.

I'd also limit the number of concurrent requests, use connection pooling carefully, and return bounded result sets.

A query that produces a million rows doesn't belong directly in an LLM context window.

For analytical questions, consider returning aggregates instead of raw records.

Reference: PostgreSQL Client Connection Defaults.

6. What If the Agent Really Needs to Modify Data?

Not every AI agent can remain read-only.

Some workflows need to update orders, create tickets, approve requests, or change account settings.

The answer isn't to give the agent unrestricted SQL execution.

It's to expose controlled business operations.

For example:

def cancel_order(order_id: int, actor_id: int, order_service): return order_service.cancel( order_id=order_id, actor_id=actor_id, ) 

The service should verify that the authenticated actor can cancel the order, that the order is in a cancellable state, and that the operation is safe to retry.

For sensitive operations, require human approval before execution.

A useful architecture is:

User Request | v AI Proposes Action | v Validate Parameters | v Check Authorization | v Human Approval (if required) | v Execute Business Service | v Audit Result 

The model can help interpret the user's request.

But the application determines whether the action is valid.

That distinction becomes increasingly important as agents gain access to more powerful tools.

7. Don't Mistake Human Approval for Security

Human-in-the-loop workflows are useful, but they introduce another subtle problem.

Imagine an agent proposes:

Cancel order #8421.

The user approves.

Before execution, the model or workflow changes the operation to cancel order #8422.

If the system only stores a Boolean approval flag, it may execute an action different from the one the human reviewed.

Approval needs to be tied to the exact structured operation.

A production workflow should preserve the approved action, its target, and relevant parameters.

If those values change, require another approval.

And even after approval, the execution service must still enforce authorization and business rules.

Human review is a control, not a replacement for secure backend design.

8. Test the Tool Boundary, Not Just the Prompt

It's easy to test an AI agent using a few normal questions and conclude that it's safe.

But the real test is whether dangerous actions remain impossible when the model behaves unexpectedly.

I'd include cases like these:

Test Expected behavior
Request another tenant's data Access denied
Ask agent to delete records No destructive tool available
Inject instructions through a document Unauthorized operation rejected
Request an excessively large result Result bounded
Trigger a slow query Timeout or resource limit enforced
Modify an approved action Reapproval required

For these tests, use a disposable database containing synthetic data.

Don't run destructive security tests against production.

I'd also log tool names, execution outcomes, latency, and authorization failures while avoiding sensitive data in logs.

The most important assertion isn't whether the LLM politely refuses a malicious instruction.

It's whether the surrounding system prevents the unauthorized operation even if the model tries to perform it.

OWASP's AI Agent Security Cheat Sheet recommends enforcing least privilege, validating tool inputs, and treating untrusted content as a potential attack surface.

9. When Arbitrary SQL Is Actually Appropriate

There are legitimate reasons to let an AI system generate SQL.

A developer-facing database assistant might need to investigate query plans, explore schemas, or help engineers write reports.

In these environments, arbitrary SQL can provide meaningful flexibility.

But I'd still limit its capabilities.

A safer development setup might use a dedicated read-only database role, an isolated replica or test database, execution timeouts, and explicit query review.

For production customer data, I'd strongly prefer predefined tools unless the application has a clear requirement for ad hoc querying.

The trade-off is straightforward.

Purpose-built tools limit flexibility but make behavior easier to understand, secure, and test.

Arbitrary SQL provides more flexibility but requires stronger isolation, validation, and monitoring.

The right choice depends on who uses the agent and what the consequences of a mistake would be.

Final Thoughts

AI agents can make database interactions more convenient, but convenience shouldn't come at the cost of security.

The biggest risk isn't always that an LLM generates incorrect SQL.

It's that the application gives the model enough authority for incorrect SQL to cause real damage.

Three lessons are worth remembering:

  1. Give agents the minimum permissions they need. Database credentials and authorization rules should enforce the boundary.
  2. Prefer controlled business tools over unrestricted SQL. Parameterized, validated operations are easier to secure and maintain.
  3. Test what happens when the model misbehaves. Reliable security depends on enforced controls, not just well-written prompts.

A well-designed AI agent should be useful even when its reasoning isn't perfect.

And when it makes a mistake, the application should limit how much damage that mistake can cause.