Build SQL Query AI Agent with Dynamic Charting in n8n

Discover how this n8n workflow empowers you to query your SQL database and dynamically generate visual charts using OpenAI and Quickchart.io, solving complex data analysis and visualization challenges easily.
agent
lmChatOpenAi
httpRequest
+7
Workflow Identifier: 1346
NODES in Use: lmChatOpenAi, executeWorkflow, executeWorkflowTrigger, httpRequest, set, chatTrigger, agent, memoryBufferWindow, informationExtractor, textClassifier
Automate SQL query 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 lets you ask questions about sales data in simple language.
It runs SQL queries automatically on a Postgres database and decides if it should create a chart.
If needed, it makes charts using Chart.js formats through Quickchart.io.
The chat shows answers and charts together quickly.
This saves time on manual reports and helps understand data better.


Who Should Use This Workflow

This is good for people who check sales or business info often but do not want to write SQL.
It helps analysts, managers, or team members who want fast, clear data answers.
You do not need to know programming; just type your question and get info.


Tools and Services Used

  • n8n workflow automation: Controls the process and nodes.
  • PostgreSQL database: Stores sales or business data to query.
  • OpenAI API (GPT-4): Creates SQL queries and chart definitions from questions.
  • Quickchart.io: Makes chart images from Chart.js settings without signup.

You can use self-host n8n for private or cheaper setups.


Inputs, Processing, and Outputs

Inputs

Processing Steps

  • Listen for user chat messages via When chat message received.
  • Extract the clear data question using Information Extractor – User question.
  • Use AI Agent to turn question into SQL query and fetch answer.
  • Classify if the answer needs a chart with Text Classifier – Chart required?.
  • If chart needed, pack question and answer to generate chart via a sub-workflow and OpenAI HTTP Request node.
  • Build chart image URL from definition using Quickchart.io.
  • Send back combined text and chart image in chat response.

Output

Clear text answer with or without a helpful chart image.
This shows quickly in chat and saves time on manual data work.


Beginner Step-by-Step: How to Use This Workflow in n8n

Step 1: Import the Workflow File

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

Step 2: Add Credentials and API Keys

  1. In n8n, add your PostgreSQL database credentials under the Credentials section.
  2. Add your OpenAI API Key also under Credentials.

Step 3: Update Configuration Details

  1. Check and update any node settings that use specific IDs, like the sub-workflow ID in Execute Workflow.
  2. If your data tables or columns have different names, update the SQL prompt or nodes accordingly.
  3. If the workflow calls email, channel, or folder names, update those too.

Step 4: Test the Workflow

  1. Run the workflow once by sending a sample message to the chat webhook URL.
  2. Check if you get a text answer and a chart if needed.
  3. Look at the execution logs to find any errors or missing info.

Step 5: Activate for Production Use

  1. Switch the workflow from “Inactive” to “Active” in n8n.
  2. Share the chat webhook URL with users who will ask data questions.
  3. Monitor workflow executions regularly for smooth operation.

If you prefer self-host n8n, import and run the workflow the same way in that environment.


Customization Ideas

  • Change chart type or colors by editing the prompt in OpenAI HTTP Request node.
  • Tweak the AI Agent’s SQL prompt for your database schema or SQL style.
  • Use other databases like MySQL or SQLite by changing credentials and prompts.
  • Increase chart size by modifying Quickchart.io URL width parameter.

Common Errors and Fixes

  • Error: SQL query fails.
    Cause: Wrong SQL syntax or table/column names.
    Fix: Check AI prompt for SQL, confirm table and column names, use double quotes for tables as needed.
  • Error: OpenAI returns bad JSON.
    Cause: Too strict output schema or incomplete JSON.
    Fix: Validate JSON, lower temperature, adjust system prompt for clear JSON.

Pre-Production Checklist

  • Confirm PostgreSQL connection and credentials work.
  • Test chat webhook by sending example messages.
  • Verify AI Agent returns good SQL queries and answers.
  • Ensure OpenAI HTTP Request returns valid Chart.js JSON.
  • Check Quickchart URLs generate visible images.

Deployment Guide

Turn the workflow Active within n8n.
Give your team the chat webhook URL to start asking questions.
Use the Executions tab for logs and to fix issues fast.


Summary

→ A simple way to ask sales data questions using chat.
→ Auto SQL queries and text answers from Postgres data.
→ Automatic decision when chart needed and chart generation.
→ Combined text and chart replies in the chat interface.
→ Saves time, prevents errors, supports non-technical users.


Automate SQL query with n8n and OpenAI

Visit through Desktop to Interact with the Workflow.

Frequently Asked Questions

Yes. Update the database credentials in the AI Agent node. Adjust SQL prompts to match MySQL syntax.
Yes. Both SQL generation and chart definition requests use OpenAI API credits.
Database credentials and OpenAI API Keys are stored securely inside n8n credential storage.
Yes. Import and run the workflow on a self-hosted n8n instance. Resources like buldrr.com/hosting/ help with setup.

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.