Generate SQL Queries from Schema Only — n8n AI Agent Template
Input: natural language question + local database schema file → Processing: AI Agent generates SQL based solely on schema (no data access) → Output: SQL query and execution results (or direct answer)
- Who
- Developers or analysts who need to query databases via natural language without exposing raw data
- You get
- Ask via chat window; AI generates SQL using only schema structure, executed externally with formatted results returned; non-SQL questions get direct text answers
Constraints
Requires an n8n instance; configure openAiApi and mySql credentials. Before first run, prepare a MySQL server and import your database (the template example uses Chinook, available on GitHub). Execute the top half of the workflow once to fetch and save the schema locally. Subsequent chat triggers read this local file instead of reconnecting to the remote database.
What they did
Author yulia modified a previous SQLite SQL Agent template into a security-focused variant: the AI Agent only accesses database schema, never actual data. By executing SQL outside the AI Agent node and preventing results from flowing back, data confidentiality is preserved. The workflow splits into a one-time schema download (top half) and chat query (bottom half), using Window Buffer Memory to maintain conversation context.
How it went
Published on n8n.io, the author reports this approach as "more secure and efficient, especially where data confidentiality is crucial." The AI can answer questions without SQL (e.g., listing tables, describing relationships) and generate SELECT queries executed by downstream nodes with formatted results. The memory node stores schema, questions, and initial replies, but not data values from SQL results (author_report).
Worth knowing
1) The core security mechanism relies on SQL executing outside the Agent and results not flowing back; modifying connections to return results to the Agent breaks confidentiality. 2) The regex extraction only matches SELECT...; patterns; complex multi-statement queries or CTEs may fail extraction. 3) The template example uses db4free free MySQL service; production environments should use an owned database with updated credentials. 4) This workflow has not been tested by our site (reproduction=not_tested); verify node outputs with example questions after setup. 5) For fully manual SQL execution to preserve privacy, copy the Agent-generated SQL into a local client instead of relying on the workflow's MySQL execution node.
n8n workflow template
Structure checked · Not run-testedUse “Import from File” in n8n, or copy the JSON and paste it into the editor. Connect your own accounts, then try test data. The template is inactive by default.
Setup and test checklist
Credentials to connect
- OpenAI Chat Model node: connect OpenAI API credentials.
- List all tables in a database node: connect mySql credentials.
- Extract database schema node: connect mySql credentials.
- Run SQL query node: connect mySql credentials.
Configuration to replace
- Source template is n8n public workflow #2508 (~29 nodes). Keep inactive after import; verify triggers, expressions and external API endpoints.
- Sticky-note guidance is informational; replace placeholders with your own accounts, sheet schemas or channel IDs.
Test input and expected output
- Manually run the main path once in a test workspace and confirm credentialed nodes authenticate without errors.
- Drive one synthetic/redacted sample through and check output fields and downstream writes before enabling in production.
Template changes
- Author credential bindings, webhookId and execution data are removed; the workflow is inactive. Nodes, connections and original prompts are preserved. Not run-tested in n8n.
- No business-logic edits; verify keys, quotas and privacy compliance before use.
Template retrieved: 2026-10-24
Steps
Prepare environment and one-time schema download
1) Prepare a MySQL database and import data (template example uses Chinook dataset from GitHub). 2) Configure mySql and openAiApi credentials in n8n. 3) Run the top half of the workflow (Manual Trigger → List all tables → Extract database schema → Add table name → Convert to binary → Save file locally) to save schema as ./chinook_mysql.json. This step runs only once.
Chat trigger and load local schema
User sends a question in the Chat Trigger window. The workflow reads the locally saved ./chinook_mysql.json, extracts it as a JSON object, and merges it with sessionId, action, and chatInput from the Chat Trigger into a unified data structure for the AI Agent.
AI Agent generates SQL based on schema
The AI Agent (conversationalAgent) receives the merged data. Its input text contains the database schema and user question; the system prompt instructs the model to generate SQL using only the structure, wrap SQL commands in triple quotes, and declare that no SQL execution tool is available. Model output may contain a SQL query or a direct answer.
Execution prompt · Source text。AI Agent node parameters.text (user input template)
=Here is the database schema: {{ $json.schema }} Here is the user request: {{ $('Chat Trigger').item.json.chatInput }}Execution prompt · Source text。AI Agent node options.systemMessage (system prompt)
Assistant is a large language model trained by OpenAI. Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand. Assistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics. Overall, Assistant is a powerful system that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist. Help user to work with the MySQL database. Please wrap any sql commands into triple quotes. You don't have a tool to run SQL, so the user will do that instead of you.
Check and execute SQL query
An IF node (Check if query exists) determines if the AI Agent output contains SQL. If yes: extract the SELECT statement using regex (Extract SQL query), execute via MySQL node, then format results into a readable table. If no: route through No Operation and return the Agent's text answer directly to chat.
Execution prompt · Source text。Extract SQL query node assignments.query (regex extraction)
={{ ($json.output.match(/SELECT[\s\S]*?;/i) || [])[0] || "" }}Return final result
Merge the Agent's original response with SQL execution results (if any), format as markdown table, and present in the chat window. If no SQL was executed, only the Agent's direct answer is shown.
Prompt you can copy
Setup guidance · Editorial suggestion。Hand to setup assistant; confirm inputs and permissions first
This block is the prompt. Ads are never placed here.
You are an n8n workflow setup assistant. The user wants to replicate the "Schema-Only SQL Generation" AI Agent template. Assist in this order: 1) Confirm the user has an n8n instance and openAiApi + mySql credentials; 2) Guide importing the workflow JSON and verifying node connections; 3) Explain the need to run the top half once to save schema locally; 4) Caution that the AI Agent's systemMessage is fixed to schema-only mode and core safety constraints should not be casually modified.
To switch to PostgreSQL or another database, the principle is the same, but replace MySQL nodes with the corresponding database nodes and adjust schema extraction queries.
Source
Generate SQL queries from schema only - AI-powered · yulia · n8n.io · 2024-10-29
Comments & feedback
Tried this method? Share results, problems or improvements. Comments appear after moderation. Please avoid sensitive information.
Loading…
Agent feedback
Reports are submitted by Agents and shared after user confirmation and moderation. They are not platform-verified.