Querying your database in plain English with an n8n AI agent
Published 20 August 2026 · 5 min read
"How many orders are late this week?", "What's the average basket for customers who came from LinkedIn in July?" — questions like these usually land in a Slack channel addressed to the one person on the team who knows SQL. An n8n AI agent wired to your database can absorb a good share of that back-and-forth: it translates the question into a query, runs it, and answers in plain language with the numbers. This is a different mechanic from a classic RAG pipeline — no document chunking or embeddings involved, the agent reads your table schema directly and writes SQL on the fly. Here's how to build it properly in n8n, and more importantly, how to avoid handing the keys of your production database to a language model with no guardrails.
The outdated-tutorial trap: the SQL Agent node no longer exists
Search "n8n SQL agent" and you'll land on tutorials pointing to a dedicated SQL Agent node, filed under the LangChain root nodes. That node was removed from n8n in February 2025: any workflow still using it needs to be rebuilt. The current approach, more flexible, is to equip a standard AI Agent node with a Postgres (or MySQL) node configured as a tool rather than as a regular workflow step.
Concretely, on the Postgres node, the Usable as Tool option turns the node into a sub-node attached to the AI Agent's Tools input, the same way a custom tool is described in our guide to custom AI Agent tools. The agent then has several actions it chooses from on its own depending on the question asked: list the tables and their schema, fetch a table's detailed definition, then run the SQL query it has built. Nothing to code — the whole thing is assembled through configuration.
Building the agent step by step
- Chat Model — connect a model with reliable tool-calling (GPT-4o, Claude, Gemini). The quality of the generated SQL depends directly on this, as detailed in our AI Agent node guide.
- Postgres in tool mode — add the node, enable Usable as Tool, and give it a clear description of what it covers ("Sales database: orders, customers, products"). That description is what the model reads to decide when to call it.
- System message — specify the SQL dialect (PostgreSQL), a default row limit ("always add LIMIT 50 unless a larger volume is explicitly requested"), and above all the business rules that aren't in the schema: which order status means "delivered," which column is the source of truth for revenue net of discounts. This is exactly the old role of the
top_kanddialectvariables the now-defunct SQL Agent node used to require — except today you write them into the prompt yourself instead of filling in a dedicated field. - Output Parser (optional) — if the results need to feed a formatted Slack message, a spreadsheet row, or an email, constrain the output with a Structured Output Parser rather than parsing free-form text downstream.
Securing access: the SQL role comes before the prompt
This is the point most tutorials wave away in a single sentence, even though it's the only one that really matters. The old SQL Agent node blocked DML statements (INSERT, UPDATE, DELETE, DROP) by default at the agent-prompt level. A generic AI Agent paired with a Postgres node in tool mode has no such protection by default: if the credential in use has write permissions, the agent can technically write.
The only reliable barrier lives in the database, not in the prompt:
CREATE ROLE agent_readonly LOGIN PASSWORD '...';
GRANT CONNECT ON DATABASE myapp TO agent_readonly;
GRANT USAGE ON SCHEMA public TO agent_readonly;
GRANT SELECT ON orders, customers, products TO agent_readonly;
This dedicated role, attached to the Postgres node's credential, guarantees that no query generated by the agent — even a malformed or manipulated one — can modify a single row. It's the principle of least privilege applied to the letter: expose only the tables the intended use actually needs, never the whole schema for convenience. Our guide on securing API credentials walks through the same logic for other connectors.
A second, subtler risk: an agent that reads the content of your data (a free-text customer comment field, for instance) can be exposed to indirect injection if that content gets fed back into a reply or a later reasoning step — the mechanism documented by Greshake et al. (2023) in their work on indirect prompt injection, available on Google Scholar. A read-only role limits the possible damage, but doesn't excuse you from filtering outputs if the agent is exposed to external users — see our dedicated article on prompt injection and n8n guardrails.
Limits worth knowing before shipping this to production
A text-to-SQL agent isn't infallible, even with today's best models. The reference research benchmark, Spider (Yu et al., EMNLP 2018, see on Google Scholar), was built precisely because translating a question into correct SQL gets noticeably harder once the schema is unknown to the model, spans several linked tables, and has ambiguous column names — which describes a real production database fairly well, as opposed to a two-table demo. Two practical implications:
- Test with real questions, not just simple cases like "how many customers in France." Three-table joins and conditional aggregations are where the errors show up.
- Surface the generated query, not just the result — a simple
additionalOutputfield or a log in the target channel lets a human catch a wrong query before it becomes a bad business decision.
Concrete use cases
- Internal Slack support: an agent that replies "order #4521 has been shipped since Tuesday" without a human opening the CRM.
- Ad hoc reporting: replacing one-off "can you pull me a number" requests to the data team with a self-service, read-only channel.
- Complementing an audit trail: pairing the agent with the same Postgres/Supabase database that feeds the audit workflow in the Compliance & Audit Pack (€149), to query the already-logged history in plain language instead of writing SQL for every check.
If your need is around documents rather than structured tables — PDFs, contracts, a knowledge base — that's a different problem: see our RAG guide with Supabase and the RAG Assistant Pack (€119), which covers ingestion, semantic search and sourced answers rather than generated SQL.
A well-built text-to-SQL agent saves real time for a team drowning in one-off number requests. But its value depends entirely on how rigorously it's set up: a read-only SQL role, a restricted table scope, and business rules spelled out in the system message rather than assumed to be obvious.
FAQ
Frequently asked questions
Does the SQL Agent node still exist in n8n?
No. n8n used to ship a dedicated SQL Agent node (under the LangChain root nodes category), removed in February 2025. If a tutorial or video still points to it, it's outdated: the current approach is to attach a regular Postgres or MySQL node in tool mode ("Usable as Tool") to a standard AI Agent node, with the Execute Query, Get DB Schema and Tables List, and Get Table Definition operations made available to it.
How do I secure an AI agent that has access to my database?
The non-negotiable rule: create a dedicated SQL role, applied to the node's credential, with SELECT-only rights on the relevant tables (REVOKE INSERT, UPDATE, DELETE, DROP). Never rely on the system message alone to prevent writes — a natural-language instruction can still be bypassed by a clever phrasing or an indirect injection, whereas a SQL role with no write permission is a barrier the agent technically cannot cross.
Can an AI agent get complex SQL queries wrong?
Yes, regularly, as soon as the schema has ambiguous joins, similarly named columns, or unwritten business rules (which status counts as a "cancelled order"?). The Spider research benchmark (Yu et al., EMNLP 2018), which specifically evaluates natural-language-to-SQL translation on multi-table schemas unseen by the model, illustrates well why this remains an active research problem: real schemas are more ambiguous than the questions suggest. Always give the system message the business definitions that aren't in the schema itself.
Does this work with MySQL, or only Postgres?
Both. n8n's MySQL node offers the same "Usable as Tool" mode as the Postgres node, with equivalent operations. The security approach (read-only role, limited table scope) applies identically regardless of the database engine.
Bundle FlowKit Complet
€269