Skip to content

About

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.

Resources

Stars

65 stars

Watchers

1 watching

Forks

Latest commit

 

History

11 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

n8n NL2SQL Intelligent Data Query Workflow

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.

Workflow (nl2sql.json)

Workflow Screenshot (Workflow Screenshot)

Workflow (nl2sql_2.0.json)

Workflow Screenshot (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.)

UI Showcase

Example of embedding in my local business system

Workflow Screenshot (Result 1)

Workflow Screenshot (Result 2)

Workflow Screenshot (Result 3)

✨ Core Features

  • 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.

⚙️ How It Works

The workflow follows a sophisticated multi-step process:

  1. Receive Request: The Webhook node receives the question sent by the user via a POST request, along with an optional sessionId.
  2. Get Context: The workflow retrieves historical conversation records based on the sessionId and dynamically queries the database to get the latest table schema information.
  3. 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.
  4. 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.
  5. 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.

🚀 Quick Start

Please follow the steps below to set up and run this workflow in your own n8n environment.

1. Prerequisites

  • 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).

2. Import Workflow

  1. Download the nl2sql.json file from this project.
  2. In your n8n canvas, click "Import" -> "From File".
  3. Select the nl2sql.json file you just downloaded to import it.

3. Configure Credentials

You need to set up credentials for two key nodes in the workflow:

  • Database Nodes:

    1. Find the two PostgreSQL nodes named Get DB Schema and Execute Generated SQL.
    2. 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.
  • Large Language Model (LLM) Node:

    1. Find the node named DeepSeek Chat Model (or the model you wish to use).
    2. Click the node, and in the "Credential" field, select or create a new credential and enter your LLM API Key.
    3. You can replace this node with any other LLM node supported by n8n that you prefer.

4. Customize Database Schema Query

This is the most critical step; you need to tell the workflow which tables to analyze.

  1. Find the node named Get DB Schema.

  2. Click the node and view its Query parameter.

  3. Modify the WHERE clause in the SQL query to match your schema and the table_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

agent.html Usage Guide

A test entry point is provided. You can customize it or decide whether to use it based on your needs.

How to Use

Open agent.html directly in your browser, and you will see the page below.

Workflow Screenshot (Test Interface Screenshot)

Configure your n8n Service

Configure your n8n address inside the HTML file.

webhookUrl: 'http://localhost:5678/webhook-test/57c8f04e-beee-4510-ba9b-cab0d331563d',

Test Result

Workflow Screenshot (Test Result Screenshot)

How to Integrate into Your Web System

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>

🔧 Customization & Extension

  • Switch Database: Replace the PostgreSQL nodes 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 the AI Agent system prompt.
  • Change LLM: Simply replace the LLM nodes connected to the AI Agent and Charts Agent.
  • Optimize Prompt: You can edit the system prompts within the AI Agent and Charts Agent nodes to better suit your business terminology or specific query style.

How to Optimize Results

  • 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, gemini performed better than deepseek, but I had to choose deepseek due 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.

Credits

The prompt format for the workflow was referenced from SQLBot.

🤝 Contribution

Issues and Pull Requests are welcome to improve this workflow!

Linux Do

Star History

Star History Chart

About

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.

Resources

Stars

65 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages