Checklist: Securing Database Access for AI Agents
When an AI agent runs SQL against a company database, the queries are no longer decided by application code alone. A language model decides too, and text can steer it. This checklist covers the safeguards that matter specifically for databases. The examples use PostgreSQL (documentation as of November 2026); the principles carry over to other engines.
Who is this checklist for?
It is written for IT and security leads asked to sign off an agent with read or write access to a database. It focuses on four risks specific to SQL: prompt-to-SQL injection, data leaking through broad queries, queries that exhaust the server, and unprotected personal data in columns.
For the overall architecture and when text-to-SQL makes sense at all, see Connecting an AI Agent to Databases. The hands-on setup of a read-only role with an MCP server is in Connecting PostgreSQL to an AI Agent. This checklist goes further: it tests whether the boundaries still hold when the agent has been manipulated. Generic input, output and action controls are covered in Guardrails for AI Agents.
Why is prompt-to-SQL injection a separate risk?
Classic SQL injection smuggles code through an input field. Prompt-to-SQL injection persuades the model to write the harmful SQL itself. The instruction can come straight from a user or arrive indirectly in data the agent reads, such as a support ticket or a database row.
Rodrigo Pedro and colleagues studied this class of attack in "From Prompt Injections to SQL Injection Attacks", using LangChain and seven language models, and proposed defences as framework extensions. OWASP lists prompt injection as LLM01 in its 2025 Top 10 for LLM applications and notes that it is unclear whether fool-proof prevention exists. The practical conclusion: configure the database so that even a fully compromised model can do little damage.
Identity and permissions
The strongest control is not in the agent but in the database role it logs in with. Under LLM06 Excessive Agency, OWASP explicitly recommends enforcing limits through database permissions on the identity the extension uses, rather than trusting the model.
- One role for the agent alone. No shared application account, so permissions and logs map cleanly to the agent.
- No owner, superuser or BYPASSRLS rights. The PostgreSQL documentation states that superusers and
BYPASSRLSroles always bypass row security, and table owners normally do too. - Never
pg_read_all_data. According to the docs, this predefined role reads every table, view and sequence in every schema. That is almost always too much for an agent. - Column-level grants. PostgreSQL supports
GRANT SELECT (column, …). If the agent does not need theibancolumn, it does not get it. - Row-level security for tenants and departments. After
ALTER TABLE … ENABLE ROW LEVEL SECURITY, a table without a matching policy is default-deny: no rows are visible.
CREATE ROLE agent_reader LOGIN PASSWORD :'pw' NOSUPERUSER NOBYPASSRLS;
GRANT USAGE ON SCHEMA reporting TO agent_reader;
GRANT SELECT ON reporting.orders_for_agent TO agent_reader;
-- per-session defaults
ALTER ROLE agent_reader SET default_transaction_read_only = on;
ALTER ROLE agent_reader SET statement_timeout = '5s';
Containing leaks through broad SELECTs
Read-only does not mean leak-proof. An injected instruction can tell the agent to read an entire customer table and paste it into a reply, an email or a ticket. OWASP describes this pattern under LLM02 Sensitive Information Disclosure.
- Views, not raw tables. The agent sees one view with only the columns its job needs. For views that filter rows, the PostgreSQL docs recommend the
security_barrieroption. - Decide on
security_invoker. Without it, PostgreSQL checks the view owner's privileges, not the agent's. If row-level security should apply to the agent role, setsecurity_invoker = true. - Mask personal data. Names, email addresses, phone numbers and bank details are truncated, hashed or left out. Analytics often work with a customer ID and a postcode area.
- Row cap in the tool. The tool appends a fixed
LIMITor stops reading at a ceiling, so large result sets never reach the model unfiltered. - Separate output channels. An agent that reads database content should not also be able to send data outside without approval.
Locking queries down to what is allowed
The less free-form SQL the model writes, the smaller the attack surface. For recurring questions, fixed tool functions with parameters are safer than text-to-SQL: the model supplies values, while the query lives in code.
- Bind parameters in fixed tools. The OWASP SQL Injection Prevention Cheat Sheet names parameterised queries as a primary defence. Model output is never concatenated into SQL strings.
- Allow-lists for structure. Table or sort-column names chosen by the model are mapped to fixed values.
- Free-form SQL: exactly one read statement. The tool rejects multiple statements,
SET,COPY, functions with side effects and anything other thanSELECTorWITH. - Enforce a read-only transaction in the tool. Wrap each query in
BEGIN TRANSACTION READ ONLY. The role default alone is not enough, because per-role settings in ALTER ROLE are only session defaults applied at login.
Stopping runaway queries
A model can produce a cross join over millions of rows, by accident or on instruction. That is not a leak, but it can stall the system your business runs on. Time limits inside the database and separating operational from analytical load are the remedies.
statement_timeoutaborts any statement running longer than the set time, per the PostgreSQL docs. The default is 0, meaning no limit.idle_in_transaction_session_timeoutends sessions left waiting inside an open transaction, so a crashed agent run does not hold locks.transaction_timeoutcaps the total length of a transaction, if your PostgreSQL version provides it.- Read replica or reporting database. Expensive queries do not run on the system that takes orders.
- A small, fixed connection pool. The agent cannot flood the server with parallel sessions.
Writes only with approval
Writes carry the highest risk because mistakes persist. OWASP recommends human approval for high-risk actions and granting extensions only what their purpose requires.
- No
INSERT,UPDATEorDELETEfor the read role. Writes use a second role that may only call specific functions. - Fixed functions instead of free SQL. For example
set_order_status(order_id, new_status), with allowed values checked in code. - Preview and confirm. The agent shows which rows will change; a person approves.
- Never grant
TRUNCATE. The PostgreSQL docs note thatTRUNCATEis not subject to row-level security.
Logging and testing
Without logs you cannot reconstruct which statement the model ran and what triggered it. Record the trigger, generated SQL, runtime and result size, kept apart from the returned content itself.
- Store each query with its trigger: user or event, prompt ID, SQL text, row count.
- Alert on anomalies: rejected statements, timeouts, unusually large results.
- Test regularly: plant an injected instruction in a test row and confirm the boundaries hold.
Common gaps
Protection rarely fails for lack of database features. It fails because of shortcuts during setup, and most gaps show up with a few queries against role permissions.
- The agent reuses the existing application account, which can also write.
- The view belongs to a broadly privileged owner and lacks
security_invoker, so row-level security never applies to the agent. - Read-only is only a session default, and the tool lets
SETstatements through. - The ban on dangerous statements lives only in the system prompt.
- Personal columns stay in the view because they "might be useful later".
Next step
Start with the role your agent uses today: which tables and columns can it read, can it write, does it bypass row-level security? The answers show which items on this list are missing.
If data should not leave your premises at all, consider sovereign AI with local models, where the model and its queries run on your own infrastructure.
Frequently asked questions
Does a read-only role stop prompt-to-SQL injection?
It stops changes, but not an injected prompt that reads everything the role can see. Narrow column and row rights, views and result limits are what contain that.
Can I skip parameterised queries when the model writes the SQL?
No. Fixed tool queries should still bind parameters. Free-form SQL from the model cannot be parameterised, so the database itself has to enforce the boundaries there.
Should the agent query the production database?
For analytics, a read replica or a separate reporting database is usually the better choice, so expensive queries do not slow down operational work. The same permission rules apply there.
Is a system prompt that forbids DELETE enough?
No. A prompt is guidance for the model, not a security boundary, and injected instructions can override it. Restrictions belong in grants and tool code.
Sources
- Pedro et al.: From Prompt Injections to SQL Injection Attacks (ICSE 2025) arxiv.org
- OWASP Top 10 for LLM Applications 2025: LLM01 Prompt Injection genai.owasp.org
- OWASP Top 10 for LLM Applications 2025: LLM06 Excessive Agency genai.owasp.org
- OWASP Top 10 for LLM Applications 2025: LLM02 Sensitive Information Disclosure genai.owasp.org
- OWASP SQL Injection Prevention Cheat Sheet cheatsheetseries.owasp.org
- PostgreSQL: Row Security Policies postgresql.org
- PostgreSQL: GRANT postgresql.org
- PostgreSQL: CREATE VIEW (security_barrier, security_invoker) postgresql.org
- PostgreSQL: Predefined Roles postgresql.org
- PostgreSQL: Client Connection Defaults postgresql.org
- PostgreSQL: ALTER ROLE postgresql.org