This is an n8n NL2SQL workflow that converts natural language questions into executable SQL queries. It can be embedded as an intelligent data assistant into web systems to query databases and provide visual charts for the data.
(The concept behind this version is to parse keywords from the user's question using an LLM, query the system's relevant dictionary tables based on those keywords, and attempt to guess the user's intent. Since this is a POC for demonstration, a vector database was not used, but using a vector database would normally yield better results.)
- Natural Language to SQL (NL2SQL): Ask questions in everyday language, and the workflow automatically generates the corresponding SQL queries.
- Self-Correction & Retry Mechanism: If the generated SQL fails to execute, the error information is fed back to the AI to automatically repair the query, with up to 3 retry attempts.
- Conversation Memory: The workflow remembers conversation context via
sessionId, allowing users to ask follow-up questions or engage in multi-turn dialogue. - Intelligent Chart Generation: For query results suitable for visualization, the workflow automatically generates the JSON configuration required for charts (supporting tables, bar charts, column charts, line charts, pie charts), greatly facilitating frontend application integration.
- Multi-LLM Support: You can easily switch between different Large Language Models by simply replacing the LLM node in the workflow (e.g., DeepSeek, Google Gemini, OpenAI, etc.).
- Out-of-the-box API Endpoint: The entire workflow is exposed as an API service via a Webhook node, making it easy to integrate with any of your applications.
The workflow follows a sophisticated multi-step process:
- Receive Request: The
Webhooknode receives thequestionsent by the user via a POST request, along with an optionalsessionId. - Get Context: The workflow retrieves historical conversation records based on the
sessionIdand dynamically queries the database to get the latest table schema information. - Generate SQL (Loop & Retry):
- AI Agent (SQL Generation): Integrates the user's question, conversation history, and database schema, then sends it to the LLM to generate a JSON object containing the SQL statement, recommended chart type, and table names involved.
- Execute SQL: The workflow attempts to execute the generated SQL on your database.
- Process Results:
- If successful, the data moves to the next step.
- If failed, the error information is captured and sent back to the AI Agent along with the original question, requesting a correction based on the error. This self-correction loop runs up to 3 times.
- Generate Chart Config: If the initial AI call suggests using a chart for visualization, the workflow triggers a second Charts Agent. This agent generates the detailed JSON configuration required for frontend chart rendering based on the successful SQL query results and the user's question.
- Format & Return: The workflow consolidates the final result (including query data, SQL statement, chart configuration, etc.) into a standard JSON format and returns it to the caller via the Webhook.
Please follow the steps below to set up and run this workflow in your own n8n environment.
- A running n8n instance (Cloud version or Docker self-hosted is recommended).
- Connection credentials for a PostgreSQL database.
- An API Key for a Large Language Model (LLM) (e.g., DeepSeek, Google Gemini, or OpenAI).
- Download the
nl2sql.jsonfile from this project. - In your n8n canvas, click "Import" -> "From File".
- Select the
nl2sql.jsonfile you just downloaded to import it.
You need to set up credentials for two key nodes in the workflow:
-
Database Nodes:
- Find the two PostgreSQL nodes named
Get DB SchemaandExecute Generated SQL. - Click on each node, and in the "Credential" field, select or create a new PostgreSQL credential, entering your database host, port, username, password, and database name.
- Find the two PostgreSQL nodes named
-
Large Language Model (LLM) Node:
- Find the node named
DeepSeek Chat Model(or the model you wish to use). - Click the node, and in the "Credential" field, select or create a new credential and enter your LLM API Key.
- You can replace this node with any other LLM node supported by n8n that you prefer.
- Find the node named
This is the most critical step; you need to tell the workflow which tables to analyze.
-
Find the node named
Get DB Schema. -
Click the node and view its
Queryparameter. -
Modify the
WHEREclause in the SQL query to match yourschemaand thetable_names you want the AI to be aware of.-- Find these lines WHERE c.table_schema = 'com_time_provider' -- <-- Change to your own schema name and c.table_name in ('extern_user','external_user_superior', ... ) -- <-- Change to the list of table names you want the AI to use
A test entry point is provided. You can customize it or decide whether to use it based on your needs.
Open agent.html directly in your browser, and you will see the page below.
Configure your n8n address inside the HTML file.
webhookUrl: 'http://localhost:5678/webhook-test/57c8f04e-beee-4510-ba9b-cab0d331563d',Keep only the code inside the script tag from agent.html, save it as an agent.js file, and host this file where your system can access it.
Then integrate it into your system:
<script>
// Define your configuration here
window.NL2SQL_AGENT_CONFIG = {
// Pass your n8n Webhook URL
webhookUrl: 'http://localhost:5678/webhook/57c8f04e-beee-4510-ba9b-cab0d331563d',
// You can also override any other default settings
position: {
right: '40px',
bottom: '40px'
},
zIndex: {
chat: 1000 // Adjust layer level if necessary
}
};
</script>
<script src="http://localhost:8000/agent.js" defer></script>- Switch Database: Replace the
PostgreSQLnodes with the database nodes you use (e.g., MySQL, MSSQL, etc.). At the same time, you will need to fine-tune the SQL syntax rules (especially quoting for table and field names) in theAI Agentsystem prompt. - Change LLM: Simply replace the LLM nodes connected to the
AI AgentandCharts Agent. - Optimize Prompt: You can edit the system prompts within the
AI AgentandCharts Agentnodes to better suit your business terminology or specific query style.
- Optimize the prompt according to your business context.
- Improve your table comments and column comments in the database.
- Use a more powerful model. In my experience,
geminiperformed better thandeepseek, but I had to choosedeepseekdue to business reasons. - This is my first time using n8n, so many details in the flow can still be optimized. Feel free to modify it according to your needs; I am just providing a concept.
The prompt format for the workflow was referenced from SQLBot.
Issues and Pull Requests are welcome to improve this workflow!





