Generate SQL Queries from Database Schema with n8n AI Agent

This workflow automates SQL query generation from your MySQL database schema leveraging n8n and OpenAI’s GPT model. It enables SQL query creation based solely on schema knowledge, saving time and eliminating errors in manual query writing.
mySql
agent
lmChatOpenAi
+10
Workflow Identifier: 1263
NODES in Use: mySql, set, convertToFile, readWriteFile, extractFromFile, manualTrigger, chatTrigger, lmChatOpenAi, agent, memoryBufferWindow, if, noOp, merge
Automate SQL queries with n8n and OpenAI

Press CTRL+F5 if the workflow didn't load.

Learn how to Build this Workflow with AI:

What this workflow does

This workflow helps you ask questions in simple language and get correct SQL queries run on your MySQL database automatically.
It fixes the hard task of writing SQL by yourself and quickly gives you data answers.

You send a chat message like “Show all customers from Germany”.
The workflow uses AI with your database structure to make a SQL query.
It runs this query and sends the results back.


Who should use this workflow

This is great for people who do not know SQL very well.
Anyone who needs fast answers from a MySQL database without typing complex queries.

It helps data analysts, business teams, or anyone new to databases.
It saves time and avoids mistakes from manual query writing.


Tools and services used

Use self-host n8n if you want full control.


Inputs, processing steps, and output explained

Inputs

  • User sends a natural language question via chat.
  • Workflow has database schema loaded from a local JSON file.

Processing steps

  • Load database tables and schema once to avoid delays.
  • Receive chat input in natural language.
  • Combine the user question with the saved schema.
  • Use GPT-4 AI to create a matching SQL query.
  • Extract and verify that the SQL query is valid.
  • Run the SQL on MySQL database if valid.
  • Format results as a readable Markdown table.
  • Send back both chat answer and data results.

Output

The user gets an easy answer to their question plus actual data in clear table form.
This speeds up reports and prevents query mistakes.


Beginner step-by-step: How to use this workflow in production inside n8n

Importing the workflow

  1. Download the full workflow file using the Download button on this page.
  2. Open the n8n editor where the automation runs.
  3. Click “Import from File” and select the downloaded workflow.

Configuring the workflow

  1. Add your MySQL database credentials inside all MySQL node settings.
  2. Enter your OpenAI API Key in the LangChain AI Agent node credentials.
  3. Check table names and schema file paths if your database is different.

Testing and activating

  1. Run a test chat input by the LangChain Chat Trigger node with a sample question like “Show German customers”.
  2. Verify the workflow creates a SQL query and returns data.
  3. If successful, activate the workflow.
  4. Make sure the chat trigger webhook is public or connected to your chat system.

Now, you can ask your database questions in plain words.


Customization ideas

  • Switch database types by changing credentials and queries in all MySQL nodes to PostgreSQL or other SQL engines.
  • Modify the AI Agent’s prompt in the LangChain AI Agent node to make it answer differently or use other languages.
  • Automate refreshing the JSON schema file regularly to keep data fresh.
  • Use encrypted storage for the schema file to keep it secure.
  • Add support for multiple databases by changing the schema extraction and AI prompt.

Dealing with common problems

  • MySQL connection errors: Check username, password, host, port in MySQL nodes.
  • No SQL query generated: Make input clearer or update the AI prompt in LangChain AI Agent node.
  • Regex does not catch SQL query: Edit regex in Set node ‘Extract SQL query’ to match AI response.
  • Slow response: Confirm schema is loading from local file to avoid repeated slow database schema calls.

Pre-production checklist

  • Test database connection returns tables.
  • Verify schema extraction gathers correct columns.
  • Confirm chat trigger receives questions and AI creates SQL.
  • Check saved local JSON file for schema exists.
  • Validate AI Agent makes valid SQL queries.
  • Test workflow branching with and without queries.
  • Backup workflow and database before live use.

Deployment guide

Activate the workflow in n8n once setup and tested.
Make sure the LangChain Chat Trigger node webhook is accessible from your chat app.

Watch workflow executions panel to catch errors.
Set alerts for database or OpenAI API issues if possible.


Summary: What you achieve

✓ Save hours by not writing SQL manually.
✓ Get quick, clear data answers from your MySQL.
✓ Avoid SQL mistakes through AI validation.
✓ Help non-technical users ask questions naturally.
✓ Keep database schema handy for fast AI query generation.

→ Use the workflow in real chats for fast, accurate data insights.
→ Customize AI behavior and database connections as needed.


Code and prompt sample for AI Agent (important)

The LangChain AI Agent uses your schema and user input combined in this JSON format:

{
 "sessionId": "{{sessionId}}",
 "action": "{{action}}",
 "chatinput": "{{chatinput}}",
 "schema": "{{schemaJsonString}}"
}

This lets GPT-4 know exactly what tables and columns exist before making SQL.
A regex in the Set node ‘Extract SQL query’ looks for SELECT ... ; statements in the AI’s reply.
Use this to be sure only valid queries run on the database.


Automate SQL queries with n8n and OpenAI

Visit through Desktop to Interact with the Workflow.

Frequently Asked Questions

Check MySQL username, password, host, and port settings in all MySQL nodes. Test connection independently if needed.
The user input might be unclear or the AI prompt needs better instructions. Try making the question clearer or update the AI Agent prompt.
Yes. Replace MySQL nodes and queries with nodes for the other database type, and adjust SQL syntax accordingly.
Yes. Each call to the GPT-4 powered AI Agent consumes OpenAI API credits. Plan usage accordingly.

Promoted by BULDRR AI

Related Workflows

Automate Twist Channel Creation and Messaging with n8n

This workflow automates creating and updating a channel in Twist and sending a personalized message to specific users. It eliminates manual setup errors and saves time managing Twist communications.

Automate Ideogram Image Generation with Google Sheets & Gmail

This workflow automates graphic design image generation via Ideogram AI, storing image data in Google Sheets and Google Drive, with email alerts via Gmail. It saves designers hours by automating image creation, remixing, review, and record-keeping.

Automate IT Support with Slack and OpenAI in n8n

Streamline IT support by automating Slack message handling using n8n and OpenAI. This workflow handles Slack DMs, filters bots, queries a Confluence knowledge base, and delivers AI-generated responses, improving support efficiency and response time.

Automate Crypto Analysis with CoinMarketCap & n8n AI Agent

Discover how this unique n8n workflow leverages CoinMarketCap’s multi-agent AI to deliver precise, real-time cryptocurrency insights directly via Telegram. Manage crypto data analysis efficiently with automated multi-source API integration.

Automate Gumroad to Beehiiv Subscriber Sync with n8n

Learn how to automatically add new Gumroad sales customers as Beehiiv newsletter subscribers using n8n automation. This workflow saves time by syncing sales data to Google Sheets CRM and notifying your Telegram channel instantly.

Generate On-Brand Blog Articles Using n8n and OpenAI

This workflow automates the creation of on-brand blog articles by analyzing existing company content using n8n and OpenAI. It extracts article structures and brand voice to produce consistent draft articles, saving significant content creation time.
1:1 Free Strategy Session
Your competitors are already automating. Are you still paying for it manually?

Do you want to adopt AI Automation?

Every hour your team does repetitive work, you're burning real money.
While you wait, faster businesses are cutting costs and moving quicker.
AI and automations aren't the future anymore — they're the present.

Book a live 1-on-1 session where we show you exactly which of your daily tasks can be automated — and what it’s costing you not to.