Natural Language PostgreSQL Query Agent with GPT-4o-mini - n8n Workflow

Use this powerful n8n workflow to translate natural language questions into safe, executable PostgreSQL queries using an advanced GPT-4o-mini agent. Deploy this n8n template easily.

Workflow Preview

Ready to automate?

Download this n8n workflow template and start using it instantly.

Who is this best for?

Data Analysts & Business Users: Individuals who need quick access to PostgreSQL data without writing manual SQL. This n8n workflow simplifies data retrieval.
Automation Specialists: Users seeking advanced examples of AI agents and custom tool orchestration within an n8n environment.
Developers: Those looking for a robust n8n templates solution to expose backend databases safely via a chat interface.
Anyone leveraging the n8n node ecosystem for AI-driven database operations.

Overview

Managing and querying relational databases often requires specialized knowledge of SQL, creating a bottleneck for non-technical team members. This advanced n8n workflow solves this by deploying a sophisticated AI database agent. The agent uses the power of GPT-4o-mini to securely interpret a user's natural language request (e.g., “List all products low in stock”) and generate a schema-aware SQL query, which it then executes against a PostgreSQL database.

This specialized n8n template significantly enhances accessibility to data, allowing faster insights and decision-making. The workflow is designed to be highly secure, as the AI only executes queries against a pre-defined table, making this an ideal n8n automation solution for sensitive data environments.

How it Works

This comprehensive n8n workflow operates in a highly structured manner, leveraging several LangChain and database n8n node types:


  1. Trigger Reception: The process starts with the When chat message received n8n trigger. This node captures the user's natural language query and their session ID, which is crucial for maintaining conversation history.

  2. Table Configuration: The flow immediately passes to the Set Table Name n8n node, which hardcodes the specific target table (product_inventory) the AI agent is allowed to query.

  3. Agent Orchestration: The core logic resides in the Database Agent n8n node. This agent receives the user's input and utilizes its defined system message (the 'AI Agent Database Query System') to determine the necessary steps. This system prompt ensures safe query generation and mandates fetching the schema first.

  4. Schema Retrieval: The agent first calls the Get Table Definition PostgreSQL n8n node (configured as a tool) to retrieve the detailed schema (columns, data types, constraints) for the specified table. This grounding data is passed to the LLM.

  5. SQL Generation: The OpenAI Chat Model n8n node, running on gpt-4o-mini, uses the schema and the user's input to generate a precise SQL query.

  6. Query Execution: The agent then calls the Execute SQL Query PostgreSQL n8n node (another tool) to run the AI-generated SQL query against the database.

  7. Result Output: The PostgreSQL n8n node returns the resulting rows back to the Database Agent, which formats the data and delivers the final, clean result to the user via the chat interface, without exposing the internal SQL or tool usage.

Installation Guide

To deploy this expert n8n workflow, follow these setup steps:


  1. Import: Copy the provided JSON data and paste it into your n8n instance using the 'Import from JSON' option to create the n8n template.

  2. Credentials Setup (PostgreSQL): Configure the PostgreSQL credentials used by the Get Table Definition and Execute SQL Query n8n node connections. Ensure the credentials allow SELECT permissions on the target database.

  3. Credentials Setup (OpenAI): Add or select your OpenAI API Key credentials for the OpenAI Chat Model n8n node. This workflow utilizes gpt-4o-mini.

  4. Customize Table: Edit the Set Table Name n8n node. Update the value of the tablename assignment to match the exact name of the table you wish to query (currently set to productinventory).

  5. Activate: Save the n8n workflow and activate it using the toggle switch. The When chat message received n8n trigger will then be live and awaiting inputs via the chat UI.

Node Details

When chat message received (n8n trigger): The entry point of this n8n workflow. It initiates the automation whenever a user sends a message to the associated chat endpoint, supplying the input text and session ID.
Set Table Name (n8n node): A utility node that defines a context variable (tablename: productinventory). This ensures the AI agent only operates on the intended database table, enhancing security and focus.
OpenAI Chat Model (n8n node): Configured to use GPT-4o-mini. It serves as the Large Language Model engine, translating the user request and schema context into executable SQL.
Simple Memory (n8n node): Utilizes a Buffer Window memory type, keyed by the session ID from the n8n trigger. This allows the agent to recall previous conversational turns, enabling follow-up questions within the same chat session.
Get Table Definition (Postgres n8n node): Acts as a crucial tool for the AI agent. It executes a complex query to fetch column names, data types, and constraints for the dynamic table name, grounding the AI's query generation.
Execute SQL Query (Postgres n8n node): The primary execution tool. It accepts the dynamically generated SQL from the AI ({{ $fromAI("sql_query", "SQL Query") }}) and runs it against the PostgreSQL database, returning the resulting records.


  • Database Agent (n8n node): The core control unit. It orchestrates the flow: receiving input, fetching schema, calling the LLM for query generation, and executing the query using the provided PostgreSQL n8n node tools. Its system prompt dictates a strict, secure SQL generation process.

Related n8n Workflows

Free

Nodes: 7 Nodes
Updated: December 26 2025
View all
Created by

I’m currently obsessed with building cool things using AI automation and AI agents — systems that save time, cut manual work, and actually do stuff on their own. If there’s a way to automate it, I’m probably already trying it out (or planning to). Having worked in IT industry for 15 years, I’m combining that background with AI to help businesses move smarter, not just faster.

Featured*