Skip to main content

Query PostgreSQL database with natural language using GPT-4o-mini

Workflow preview

Workflow preview
100%
Query PostgreSQL database with natural language using GPT-4o-mini preview
Open on n8n.io

Important notice

This workflow is provided as-is. Please review and test before using in production.

1. Workflow Overview

This Database SQL Query Agent convert natural language into sql query to get results Turn your PostgreSQL database into a conversational AI agent! Ask questions in plain English and get instant dat...

Best for

  • AI Chatbot automation workflows
  • Multimodal AI automation workflows
  • intermediate n8n builders looking for reusable templates

Tools used

@n8n/n8n-nodes-langchain.chattrigger, n8n-nodes-base.stickynote, n8n-nodes-base.set, @n8n/n8n-nodes-langchain.lmchatopenai, @n8n/n8n-nodes-langchain.memorybufferwindow, n8n-nodes-base.postgrestool, @n8n/n8n-nodes-langchain.agent

Source and attribution

This workflow is cataloged by N8N Workflows and links back to its original n8n.io source page by Babish Shrestha.

Original n8n.io source

1.1 Workflow description

Title
Query PostgreSQL database with natural language using GPT-4o-mini
Workflow name
Query PostgreSQL database with natural language using GPT-4o-mini

This Database SQL Query Agent convert natural language into sql query to get results

Turn your PostgreSQL database into a conversational AI agent! Ask questions in plain English and get instant data results without writing SQL.

✨ What It Does

  • Natural Language Queries: "Show laptops under $500 in stock" → Automatic SQL generation
  • Smart Column Mapping: Understands your terms and maps them to actual database columns
  • Conversational Memory: Maintains context across multiple questions
  • Universal Compatibility: Works with any PostgreSQL table structure

🎯 Perfect For

  • Business analysts querying data without SQL knowledge
  • Customer support finding information quickly
  • Product managers analyzing inventory/sales data
  • Anyone who needs database insights fast

🚀 Quick Setup

Step 1: Prerequisites

  • n8n instance (cloud/self-hosted)
  • PostgreSQL database with read access
  • OpenAI API key/You can use other LLM as well

Step 2: Import & Configure

  1. Import this workflow template into n8n
  2. Add Credentials:
    • OpenAI API: Add your API key
    • PostgreSQL: Configure database connection
  3. Set Table Name: Edit "Set Table Name" node → Replace "table_name" with your actual table
  4. Test Connection: Ensure your database user has SELECT permissions

Step 3: Deploy & Use

  1. Start the workflow
  2. Open the chat interface
  3. Ask questions like:
    • "Show all active users"
    • "Find orders from last month over $100"
    • "List products with low inventory"

🔧 Configuration Details

Required Settings

  • Table Name: Update in "Set Table Name" node
  • Database Schema: Default is 'public' (modify SQL if different)
  • Result Limit: Default 50 rows (adjustable in system prompt)

Optional Customizations

  • Multi-table Support: Modify system prompt and add table selection logic
  • Custom Filters: Add business rules to restrict data access
  • Output Format: Customize response formatting in the agent prompt

💡 Example Queries

E-commerce

"Show me all electronics under $200 that are in stock"

HR Database

"List employees hired in 2024 with salary over 70k"

Customer Data

"Find VIP customers from California with recent orders"

🛡️ Security Features

  • Read-only Operations: Only SELECT queries allowed
  • SQL Injection Prevention: Parameterized queries and validation
  • Result Limits: Prevents overwhelming queries
  • Safe Schema Discovery: Uses information_schema tables

🔍 How It Works

  1. Schema Discovery: Agent fetches table structure and column info
  2. Query Planning: Maps natural language to database columns
  3. SQL Generation: Creates safe, optimized queries
  4. Result Formatting: Returns clean, user-friendly data

⚡ Quick Troubleshooting

  • No Results: Check table name and ensure data exists
  • Permission Error: Verify database user has SELECT access
  • Connection Failed: Confirm PostgreSQL credentials and network access
  • Unexpected Results: Try more specific queries with exact column names

🎨 Use Cases

  • Inventory Management: "Show low-stock items by category"
  • Sales Analysis: "Top 10 products by revenue this quarter"
  • Customer Support: "Find customer orders with status 'pending'"
  • Data Exploration: "What are the unique product categories?"

🔧 Advanced Tips

  • Performance: Add database indexes on frequently queried columns
  • Customization: Modify the system prompt for domain-specific terminology
  • Scaling: Use read replicas for high-query volumes
  • Integration: Connect to Slack/Teams for team-wide data access

Tags: AI, PostgreSQL, Natural Language, SQL, Business Intelligence, LangChain, Database Query

Difficulty: Beginner to Intermediate
Setup Time: 10-15 minutes

1.2 Logical Blocks

This catalog entry is organized from the workflow JSON. The node-level section below shows the executable blocks available for review before importing the template.

2. Block-by-Block Analysis

Block 1 - When chat message received

Type / Role
@n8n/n8n-nodes-langchain.chatTrigger - chatTrigger
Config choices
Version 1.1

Block 2 - Sticky Note

Type / Role
n8n-nodes-base.stickyNote - stickyNote
Config choices
Version 1

Block 3 - Set Table Name

Type / Role
n8n-nodes-base.set - set
Config choices
Version 3.4

Block 4 - OpenAI Chat Model

Type / Role
@n8n/n8n-nodes-langchain.lmChatOpenAi - lmChatOpenAi
Config choices
Version 1.2

Block 5 - Simple Memory

Type / Role
@n8n/n8n-nodes-langchain.memoryBufferWindow - memoryBufferWindow
Config choices
Version 1.3

Block 6 - Execute SQL Query

Type / Role
n8n-nodes-base.postgresTool - postgresTool
Config choices
Version 2.5

Block 7 - Get Table Definition

Type / Role
n8n-nodes-base.postgresTool - postgresTool
Config choices
Version 2.5

Block 8 - Database Agent

Type / Role
@n8n/n8n-nodes-langchain.agent - agent
Config choices
Version 2

Block 9 - Sticky Note1

Type / Role
n8n-nodes-base.stickyNote - stickyNote
Config choices
Version 1

3. Summary Table

Workflow Query PostgreSQL database with natural language using GPT-4o-mini
Complexity intermediate
Nodes 9
Categories AI Chatbot, Multimodal AI
Author Babish Shrestha
Published 28 Aug 2025

4. Reproducing the Workflow from Scratch

  1. 1. Download the workflow JSON

    Use the JSON export at /data/workflows/7988/7988.json as the source template for this automation.

  2. 2. Import the template into n8n

    Open n8n, import the downloaded JSON, and review each node before activating the workflow.

  3. 3. Configure credentials and variables

    Replace placeholder credentials, API keys, webhook URLs, account IDs, and environment-specific values with your own settings.

  4. 4. Test with sample data

    Run the workflow manually or in a staging workspace, inspect node output, and confirm downstream systems receive the expected data.

  5. 5. Activate and monitor

    Enable the workflow only after testing, then monitor executions, errors, and rate limits during the first production runs.

5. General Notes & Resources

Review imported nodes carefully before activation. This catalog entry is intended to help you inspect the workflow structure, understand required services, and find related templates faster.

Node names, credentials, schedules, webhook paths, and external service limits may need adjustment for your workspace.

Frequently asked questions

What does Query PostgreSQL database with natural language using GPT-4o-mini do?

This Database SQL Query Agent convert natural language into sql query to get results Turn your PostgreSQL database into a conversational AI agent! Ask questions in plain English and get instant dat...

What do I need before importing this workflow?

Review the workflow JSON, configure any required credentials in n8n, and test the automation in a safe workspace before using it in production.

Can I customize this workflow?

Yes. Use the block-by-block analysis and the downloadable JSON to inspect each node, then adjust credentials, prompts, schedules, filters, or destinations for your AI Chatbot, Multimodal AI use case.