Chat with PostgreSQL Database Using n8n and AI Agent

Discover how this n8n workflow enables real-time chat interaction with your PostgreSQL database using AI. It automates SQL query generation and execution, saving hours on data analysis and improving decision-making accuracy.
agent
chatTrigger
postgresTool
+3
Workflow Identifier: 1703
NODES in Use: chatTrigger, agent, lmChatOpenAi, postgresTool, memoryBufferWindow, stickyNote
Chat with PostgreSQL using n8n and AI

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

Learn how to Build this Workflow with AI:

What this workflow does

This workflow lets users chat with a PostgreSQL database using natural language inside n8n. It solves the problem of writing SQL queries manually by automatically generating correct queries from user questions. The result is fast, accurate answers without needing SQL knowledge.

You send a question in plain English. The AI reads the question, finds the right database tables and columns, makes SQL code, runs it, and returns useful data. It keeps conversation history to answer follow-up questions with context.


Who should use this workflow

Anyone who needs data from a PostgreSQL database but does not want to write SQL queries.

This helps data analysts, team members without technical skills, or business users who want quick database answers by chatting.


Tools and services used


Workflow input → process → output

Input

A user sends a chat message with a question about the data.

Processing steps

  • The When chat message received node listens for the message.
  • The AI Agent node reads the question and uses database schema info tools to build a correct SQL query with schema prefixes.
  • The AI Agent runs schema and table list queries with Get DB Schema and Tables List node.
  • For detailed table info, it uses Get Table Definition node.
  • Then the AI Agent sends the SQL query to Execute SQL Query node to get data.
  • The Chat History node keeps past interaction context so AI can answer follow-ups.
  • The OpenAI Chat Model node runs the GPT model (by default, gpt-4o-mini) to generate human-like responses.

Output

Users get an immediate answer based on data extracted from the database without writing SQL.


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

Step 1: Import the workflow

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

Step 2: Add credentials

  1. Go to Credentials in n8n settings.
  2. Enter your PostgreSQL connection details (host, port, user, password, database).
  3. Enter your OpenAI API key under OpenAI API credentials.

Step 3: Check node settings

  1. Verify database details in Postgres Tool nodes.
  2. Check the AI Agent node has the right system message prompt instructing to use schema prefixes in SQL.
  3. Confirm the OpenAI Chat Model node uses the desired GPT model, by default gpt-4o-mini.

Step 4: Test the workflow

  1. Use the webhook URL from the When chat message received node to send a sample chat message, for example: “Show total customers by country.”
  2. Check if you get an immediate, correct answer.

Step 5: Activate the workflow

  1. Turn on the workflow in n8n by toggling its active status.
  2. Now the chat interface is ready for use in production.

If interested in security or compliance, consider self-host n8n for this setup.


Customizing the workflow

  • Change the OpenAI model in the OpenAI Chat Model node to gpt-4 or gpt-3.5-turbo to balance cost and accuracy.
  • Adjust the conversation history length in the Chat History node to keep more or less past messages.
  • Edit SQL in the Get DB Schema and Tables List or Get Table Definition nodes to limit schemas or add extra fields.
  • Add authentication to the webhook if sharing the chat publicly to secure access.
  • Modify the AI Agent’s system message to change answer style, for example to tables or JSON format.

Common errors and fixes

  • Error: SQL errors caused by missing schema prefixes
    Fix: Edit the AI Agent node prompt to always add schema before table names. Test with simple queries first.
  • Error: Webhook triggers but no reply
    Fix: Check workflow node connections and logs. Verify credentials for OpenAI and Postgres.
  • Error: OpenAI API rate limit exceeded
    Fix: Limit chat usage or switch to less costly models like gpt-3.5-turbo.

Summary of benefits

✓ Easily ask PostgreSQL data questions in plain English and get SQL-based answers.

✓ Save time by skipping manual SQL query writing and debugging.

✓ Help non-technical users get data insights without learning SQL.

✓ Maintain conversation context for follow-up questions.

→ Speed up team decisions with instant database access.


Chat with PostgreSQL using n8n and AI

Visit through Desktop to Interact with the Workflow.

Frequently Asked Questions

No, this workflow uses PostgreSQL-specific nodes and SQL queries. Adapting it to other databases needs changing SQL code and nodes accordingly.
API credit use depends on how often chat messages are sent and which GPT model is selected. Smaller models like gpt-3.5-turbo use fewer credits.
Security depends on proper credential management and deployment setup. Using self-host n8n and restricting webhook access improves security.
Errors often happen when AI generates queries without schema prefixes. Ensuring the AI Agent system message instructs adding schema names fixes this.

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.