AI-Powered SQL Query Generation with n8n and MySQL Schema

Discover how this n8n workflow uses AI to generate SQL queries from a MySQL database schema, enhancing query accuracy and saving time by automating database interactions. Learn to automate schema extraction, query formation, and execution seamlessly.
mySql
lmChatOpenAi
agent
+10
Workflow Identifier: 1312
NODES in Use: mySql, set, convertToFile, readWriteFile, extractFromFile, chatTrigger, lmChatOpenAi, agent, memoryBufferWindow, noOp, if, merge, stickyNote
Automate SQL queries with n8n and MySQL

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

Learn how to Build this Workflow with AI:

What This Automation Does

This workflow turns simple text requests into exact SQL queries using your MySQL database schema and AI.

It solves slow, error-prone manual querying by automating query creation just from the schema, without needing direct data access.

The result is fast, correct SQL queries and clear answers shown together.


Who Should Use This Workflow

This is for data users who are not SQL experts but need to get data from complex MySQL databases.

It fits teams with limited SQL skills or people who want to save time and avoid query mistakes.

It also works well if database is slow or schema is big because schema is saved locally for quick reuse.


Tools and Services Used

  • MySQL: Stores your data and schema structure.
  • OpenAI GPT-4o via LangChain: Generates SQL queries from schema and user text.
  • n8n nodes: MySQL, LangChain OpenAI Chat Model, LangChain AI Agent, File Read/Write, Set, If, Merge.

Inputs, Process, and Output

Inputs

  • Natural language query from a user via chat.
  • Database schema extracted from MySQL.

Processing Steps

  • Fetch and save schema of all tables locally to avoid repeated remote calls.
  • On user query, load saved schema and combine with user text.
  • Use AI agent to make SQL SELECT query from the schema only.
  • Extract SQL query from AI text carefully using regex inside Set node.
  • Check if valid query exists using If node.
  • Run SQL query on database.
  • Format SQL result as readable table string.
  • Combine AI textual answer and query results for final output.

Output

  • Readable SQL query results (in table format).
  • AI-generated explanation or context answering the input question.

Beginner Step-by-Step: Using This Workflow in n8n Production

Step 1: Import the Workflow

  1. Download the workflow file using the Download button on this page.
  2. Open your n8n editor where you want to run the workflow.
  3. Click on “Import from File” and select the downloaded workflow file.

Step 2: Configure Credentials and Settings

  1. Add your MySQL database credentials if not already added in n8n.
  2. Add your OpenAI API Key with GPT-4o access under credentials.
  3. Update any database names, table names, or file paths in nodes if your setup differs.

Step 3: Test the Workflow

  1. Send a sample natural language query to the chat webhook URL created by the LangChain Chat Trigger node.
  2. Check the workflow run inside n8n’s execution panel for errors and results.

Step 4: Activate for Production

  1. Once testing is successful, toggle the Enable switch in n8n to activate the workflow.
  2. Use the webhook URL to receive and process live user queries.
  3. Optionally, schedule periodic schema extraction to keep schema data updated.

For better control, consider self-host n8n to run this on your own server.


Common Issues and Fixes

  • MySQL connection errors: Check that database host, username, and password are correct.
  • AI agent missing SQL query: Make sure schema JSON is passed correctly and prompt includes it fully.
  • File read/write errors: Confirm file paths and that n8n has needed system permissions.
  • Slow schema extraction: Be sure to save schema locally and reload saved JSON on each query.

Customization Ideas

  • Change your database by updating MySQL credentials and queries in nodes.
  • Adjust AI temperature in LangChain nodes to change query creativity level.
  • Modify regex in Set nodes to extract other SQL commands if needed.
  • Use caching nodes to store AI-generated queries for repeated user questions.

Summary of Benefits and Results

✓ Faster, error-reduced SQL query creation from natural language.

✓ Stored database schema locally improves response times and reduces remote calls.

✓ Non-technical users can write SQL queries using easy chat messages.

→ Workflow delivers both SQL results and AI answers together.


Automate SQL queries with n8n and MySQL

Visit through Desktop to Interact with the Workflow.

Frequently Asked Questions

The MySQL node fetches the database tables and executes SQL queries, both for schema extraction and query execution generated by AI.
The workflow provides the AI agent with the complete database schema in JSON form and strict prompt instructions, so the AI makes SQL queries only based on schema.
Check that the JSON schema file loads correctly and is combined with the user chat input before sending to the AI agent. Also verify prompt formatting.
Import the workflow into the n8n editor, configure MySQL and OpenAI credentials, adjust IDs or paths, test with a sample query, then enable the workflow for live use.

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.