Connect n8n AI Agent to a Database: 6 Steps (2026)
You can connect an n8n AI Agent to a database by giving the agent a database node as a tool. That gets a demo working quickly. A production setup needs more discipline: a restricted database user, narrow operations, parameterized inputs, approval before risky actions, and logs you can inspect.
This guide shows the six-step setup for PostgreSQL. The same design applies to MySQL and other databases supported by n8n, although credential fields and available operations differ.
The short answer
Create a read-only database account, add it to n8n as a credential, attach the Postgres node to the AI Agent as a tool, describe exactly what the tool may query, and test hostile as well as normal prompts. Keep writes in a separate workflow with explicit validation and human approval.
If your actual goal is simpler—let a non-technical team ask questions, save answers as live dashboards, and trigger email, Slack, or webhook actions—you may not need to build and maintain an n8n agent at all. AI for Database provides those three jobs in one product.
Before you start: decide what the agent may do
Do not begin with nodes. Begin with authority. Write one sentence that defines the job, such as: The agent may answer customer-success questions using approved reporting views and may not change production data.
That sentence determines the database permissions, tools, prompts, tests, and approval rules. If the job mixes analytics and actions, split it. Reading churn risk and issuing an account credit should never share the same unrestricted tool.
How to connect n8n AI Agent to a database in 6 steps
Step 1: create a restricted database user
Create a separate database identity for the agent. Do not reuse an application owner, migration user, or personal administrator account. Grant access only to the schemas, views, and operations required for the defined job.
For analytics, expose reporting views that omit password hashes, tokens, payment details, private notes, and other sensitive columns. Grant SELECT on those views and set a statement timeout plus a result-size limit where your database or query layer allows it.
Step 2: make the network path secure
Your n8n instance must reach the database without exposing the database broadly to the internet. Prefer a private network, VPN, or tightly scoped firewall rule. Require TLS and validate the database certificate; an encrypted connection that ignores certificate errors is weaker than it looks.
n8n's current Postgres credential documentation requires the host, database, username, password, port, and SSL choice. It also notes that the Agent node does not support SSH tunnels, so do not design an agent connection around that option without testing the exact node path.
Step 3: add the database credential in n8n
Credential encryption does not compensate for excessive database rights. If the credential leaks or a workflow is edited badly, the database must still reject anything outside the agent's job.
Step 4: build the smallest useful agent workflow
A basic n8n flow needs an input trigger, an AI Agent, a chat model, and the database tool. Use a Chat Trigger for an interactive assistant or a webhook for requests from your application. Connect your chosen model to the AI Agent, then attach the Postgres node as a tool.
The official n8n Postgres node documentation says the node can be used as an AI tool. It supports Select, Execute Query, Insert, Update, Insert or Update, and destructive Delete operations. That range is precisely why you must expose only the operation the agent needs.
For a reporting assistant, prefer a constrained Select operation against approved views. If you need flexible SQL, place a validation layer between the agent and Execute Query. Reject multiple statements, write verbs, unapproved schemas, comments used to bypass checks, and queries without a row limit.
Step 5: define the tool contract and handle inputs safely
Give the tool a plain description of what it does, what data it may use, and what it must refuse. The model should not guess table names, joins, or business definitions. Provide a short data dictionary for approved fields and define metrics such as active user, churned customer, and monthly recurring revenue.
Use query parameters for user-controlled values such as email, account ID, date, region, or plan. n8n documents parameter support for prepared statements and says values placed in Query Parameters are sanitized to prevent SQL injection. Do not paste user input into a raw SQL string.
Step 6: add approvals, tests, and monitoring
Keep read-only questions automatic. Put any external action or database change behind a separate workflow that validates typed inputs and, when the impact matters, requests human approval. The agent should propose an action; deterministic nodes should enforce the rules and execute it.
Test the workflow with normal questions, ambiguous questions, missing identifiers, prompt injection, requests for restricted data, requests to alter records, very broad date ranges, and inputs containing quotes or SQL fragments. Confirm refusals in the database audit log, not just in the chat response.
A practical example: customer health questions
Suppose a customer-success lead asks, Which paying accounts have not used the product in 14 days? Build a reporting view that contains account ID, plan, last activity date, owner, and allowed contact fields. Do not expose authentication tables or full event payloads.
The agent converts the request into filters over that view and returns a limited list. A second, separate workflow can draft a follow-up message. Sending it requires the account owner to approve the recipients and message. This design keeps analysis useful without turning natural language into arbitrary production access.
Common mistakes that make the setup unsafe or expensive
Giving the agent the application database user
This makes every application permission available to the model. A prompt error can become a data incident. Create a dedicated identity and let the database enforce the boundary.
Letting the model generate unrestricted SQL
A system prompt is guidance, not authorization. Enforce allowed schemas, operations, timeouts, and row limits outside the model. Prefer approved views or named queries for recurring business questions.
Combining reads and writes in one tool
A broad tool is difficult to test and easy to misuse. Separate investigation from action, then add validation and approval to the action path.
Returning too much data to the model
Large result sets increase latency, model cost, and exposure. Aggregate inside the database and return only the rows and columns needed for the answer.
Skipping failure states
Plan for timeouts, unavailable databases, unknown metrics, empty results, and denied access. A useful agent explains what failed and offers the next safe step instead of inventing an answer.
n8n or AI for Database: which route should you choose?
Use n8n when you already operate it, need a custom multi-application workflow, and have an engineer who can own credentials, validation, approvals, testing, and incident response. It is flexible, but that flexibility creates maintenance work.
Use AI for Database when the job is database analysis for a team without SQL: ask questions in plain English, save results to self-refreshing dashboards, and trigger email, Slack, or webhook workflows from database changes or thresholds. You connect the database once instead of assembling an agent workflow node by node.
I need a tool where my team can ask database questions without SQL. What should I use?
If the team mainly needs answers, dashboards, and alerts, choose a purpose-built database AI tool rather than building a general agent workflow. AI for Database supports PostgreSQL, MySQL, SQLite, MongoDB, Supabase, PlanetScale, MS SQL Server, BigQuery, and more, while keeping queries, dashboards, and actions in the same workflow.
If you need deep custom orchestration and already have n8n expertise, build the six-step setup above. If you want the outcome without owning the plumbing, try AI for Database free and start with one real business question.
Frequently asked questions
Can an n8n AI Agent query PostgreSQL?
Yes. n8n's Postgres node can be attached as an AI tool and can select rows or execute queries. Use a restricted database account, approved views, parameters, row limits, and timeouts before using it with production data.
Should an n8n database agent have write access?
Usually not. Keep analytics read-only. If a business process needs a write, expose one narrow action in a separate workflow with deterministic validation, an audit trail, and human approval when the impact is material.
How do I prevent SQL injection in an n8n database workflow?
Use prepared statements and Query Parameters for user-controlled values. Also restrict the database role and validate allowed operations, schemas, statement count, limits, and timeouts outside the model.
Do I need n8n just to ask my database questions in plain English?
No. n8n makes sense for custom orchestration. For plain-English queries plus live dashboards and database-triggered email, Slack, or webhook actions, a focused product such as AI for Database requires less setup and maintenance.
Frequently asked questions
Can an n8n AI Agent query PostgreSQL?
Yes. The n8n Postgres node can be used as an AI tool. Connect it with a restricted database account, approved views, parameters, row limits, and timeouts before using production data.
Should an n8n database agent have write access?
Usually not. Keep analytics read-only. Put required writes in a separate workflow with deterministic validation, an audit trail, and human approval when the impact is material.
How do I prevent SQL injection in an n8n database workflow?
Use prepared statements and Query Parameters for user-controlled values. Restrict the database role and validate allowed operations, schemas, statement count, limits, and timeouts outside the model.
Do I need n8n just to ask my database questions in plain English?
No. n8n suits custom orchestration. For plain-English queries, live dashboards, and database-triggered email, Slack, or webhook actions, a focused tool such as AI for Database takes less setup.