Chat with PostgreSQL Database using AI Agent

Overview

This workflow creates an interactive chat interface that lets you ask natural language questions about your PostgreSQL database. Instead of writing SQL queries manually, you can simply ask questions like "Which tables are available?" or "Show me the top 10 customers by revenue" and the AI agent will generate and execute the appropriate SQL query, returning the results to you in real-time.

It's a powerful way to democratize database access for non-technical team members, reduce the time spent crafting SQL, and get instant insights from your data. The workflow uses a memory buffer to maintain conversation context, so follow-up questions can build on previous answers.

Node Breakdown

  1. When chat message received (No auth) — This is the chat trigger node that listens for incoming messages through the n8n chat interface. It processes user input and passes it to the AI agent. No authentication is required as it's a built-in n8n feature.

  2. AI Agent (No auth) — The core orchestrator that receives the chat message, processes it using the connected language model, and decides which tools to use. It uses the OpenAI Chat Model for language understanding and the Postgres tool for database queries. It also leverages the Simple Memory node to retain conversation history. No additional authentication is needed.

  3. OpenAI Chat Model (API Key auth) — Connects to OpenAI's GPT-4o-mini model to interpret user questions and generate appropriate SQL statements. Requires an OpenAI API key configured in n8n credentials.

  4. Postgres (Database credentials auth) — The PostgreSQL tool that executes SQL queries. The actual query is dynamically generated by the AI agent (using {{ $fromAI('sql_statement') }}). It requires a PostgreSQL database connection with host, port, database name, user, and password credentials.

  5. Simple Memory (No auth) — A buffer window memory that stores the last few exchanges between the user and the AI agent. This allows the agent to maintain context across multiple questions (e.g., remembering that the user asked about "customers" in the previous question).

  6. Sticky Note — A visual note that prompts the user to try the workflow by clicking the chat button and typing "Which tables are available?"

  7. Sticky Note1 — A note indicating that the PostgreSQL database can be swapped for MySQL or SQLite by replacing the Postgres node with the appropriate database node.

Setup Instructions

  • PostgreSQL Database: You need access to a PostgreSQL database. Obtain the host, port, database name, username, and password. In n8n, create a new credential of type "Postgres" and fill in the details.
  • OpenAI API Key: Sign up at OpenAI and generate an API key. Create an n8n credential of type "OpenAI" and paste your API key.
  • n8n Chat: The workflow uses the built-in n8n chat interface. Once the workflow is active, click the chat button at the bottom of the canvas to start interacting.

Use Cases and Variations

  • Database Exploration: Quickly discover schemas, tables, and sample data without writing SQL.
  • Business Intelligence: Ask ad-hoc questions like "What was the total sales last quarter?" or "Show me orders with late shipments."
  • Customer Support: Allow support agents to query customer data using natural language.
  • Variations: Replace the Postgres node with a MySQL or SQLite node to work with other databases. You can also swap the OpenAI model for another provider (e.g., Anthropic, Ollama) by changing the language model node.
7 nodesmanual triggerData
Sticky NotePostgres ToolMemory Buffer WindowAgentLm Chat Open AI

Workflow JSON

{
  "meta": {
    "instanceId": "408f9fb9940c3cb18ffdef0e0150fe342d6e655c3a9fac21f0f644e8bedabcd9",
    "templateCredsSetupCompleted": true
  },
  "nodes": [
    {
      "id": "d08a2559-17fd-4bdb-a976-795c3823a88a",
      "name": "Sticky Note",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -520,
        240
      ],
      "parameters": {
        "content": "## Try me out\nClick the 'chat' button at the bottom of the canvas and paste in:\n\n_Which tables are available?_"
      },
      "typeVersion": 1
    },
    {
      "id": "3019b559-6100-4ead-8e1a-a7dece2a6982",
      "name": "Sticky Note1",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -380,
        -60
      ],
      "parameters": {
        "color": 7,
        "width": 677,
        "height": 505,
        "content": "This workflow uses a Postgres DB, but you could swap it for a MySQL or SQLite one"
      },
      "typeVersion": 1
    },
    {
      "id": "73786411-5383-4921-82ee-06b3b582bab7",
      "name": "When chat message received",
      "type": "@n8n/n8n-nodes-langchain.chatTrigger",
      "position": [
        -320,
        40
      ],
      "webhookId": "1c0d08f0-abd0-4bdc-beef-370c27aae1a0",
      "parameters": {
        "options": {}
      },
      "typeVersion": 1.1
    },
    {
// ... truncated (copy to see full JSON)

How to Import This Workflow

  1. 1Copy the workflow JSON above using the Copy Workflow JSON button.
  2. 2Open your n8n instance and go to Workflows.
  3. 3Click Import from JSON and paste the copied workflow.

Don't have an n8n instance? Start your free trial at n8nautomation.cloud

Related Templates

Talk to Your Google Sheets Data Using OpenAI Chat Agent

This workflow transforms a Google Sheet into a live, conversational database. Using an AI agent powered by OpenAI's GPT-4.1-nano model, you can ask natural language questions about your spreadsheet data and receive accurate, context-aware answers — without writing any SQL or formulas. The agent can handle queries like total campaign spend, per-channel breakdowns, month-over-month trends, and cost-per-lead calculations. Workflow Steps Node-by-Node Breakdown Chat with Your Data (Chat Trigger) — This is the entry point of the workflow. It provides a chat interface (webhook) where users type their questions. No authentication is required to trigger the webhook; access can be secured at the workflow level. Memory (Buffer Window Memory) — Stores recent conversation history so the AI can reference previous exchanges. The buffer window keeps the last few messages to maintain context without excessive token use. No authentication required. OpenAI Chat Model (OpenAI GPT-4.1-nano) — The language model that processes user questions and generates answers. Uses API Key auth (you must provide an OpenAI API key). Parameters: model = , no additional options configured. Talk to Your Data (AI Agent) — The core agent that orchestrates the conversation. It receives user input, decides which tool to call (only the Google Sheets tool is available), and returns answers. Uses API Key auth (uses the same OpenAI credential as the model). Parameters include a system message: "Google Sheets Ask-… You are Ask-… Answer questions using Google Sheets ONLY via the tool below. Be precise and conservative. There is only one dataset. Don't ask what dataset it is. Use the data tool to answer the question." Analyze Data (Google Sheets Tool) — The tool the agent calls to read spreadsheet data. Uses OAuth2 authentication (Google Sheets). Parameters: document ID = ("Sample Marketing Data - n8n"), sheet name = "Data" (gid: 365710158). No additional options set. Sticky Notes (Information Only) — Provide setup instructions and tips. Not executable nodes. Setup Instructions Before using this workflow, you need: OpenAI Account — Visit OpenAI API Keys to generate an API key. Make sure you have billing set up at OpenAI Billing and have credits available. Google Account — You need access to a Google Sheet. The sample uses a specific sheet, but you can point it to any sheet with a similar structure: first row = column headers, rows 2–100 = data. To configure: In the OpenAI Chat Model node, create an OpenAI credential with your API key. In the Analyze Data node, create a Google Sheets OAuth2 credential (select your Google account and authorize access). Update the Document ID and Sheet Name to match your own Google Sheet. Optionally update the system message in the Talk to Your Data agent if you want to change the assistant's personality or instructions. Use Cases and Variations This workflow is perfect for: Marketing teams wanting instant answers about campaign performance, spend, and ROI. Sales operations analyzing pipeline data, deal stages, or conversion metrics. Small business owners asking questions about inventory, sales, or customer data without learning SQL. Adaptations: Replace Google Sheets with another data source tool (e.g., Airtable, Notion, PostgreSQL, MySQL) by swapping the "Analyze Data" node. Add more tools to the agent (e.g., a web search tool, a calculator) to expand its capabilities. Change the model to GPT-4o or GPT-3.5-turbo for faster/cheaper responses. Add a Slack or Webhook trigger instead of the chat trigger for a different user interface.

11 nodes

Amazon Review Monitoring with Sentiment & Telegram Alerts

High-Level Summary This workflow automatically monitors Amazon product reviews on a scheduled basis. It reads product URLs from a Google Sheet, scrapes the latest reviews using Decodo, performs sentiment analysis and summarization using Google Gemini AI, logs results back to a sheet for historical tracking, and sends a Telegram alert when negative sentiment is detected. It's ideal for e-commerce sellers, product managers, and reputation teams who want hands-off, daily review monitoring with instant notifications. Node-by-Node Walkthrough Schedule Trigger (No auth) — Runs the workflow daily (interval rule, no specific time set; can be adjusted to e.g. 9 AM). Fetches the list of product URLs from a Google Sheet. Get row(s) in sheet (OAuth2 — Google Sheets) — Reads all rows from the sheet named "list urls" in the document "decodo". Each row should contain a product URL in one column. Loop Over Items (No auth) — Splits the incoming list of URLs into batches of 5 (configurable via ). For each batch, the inner nodes (Decodo, Code, Sentiment Analyzer, Summarize, Store to Sheet) process one URL at a time. Decodo (API Key auth — Decodo service) — Scrapes Amazon product reviews for the given (passed from the sheet row). Returns structured JSON with reviewer name, rating, and review content. Code in JavaScript (No auth) — Transforms the raw Decodo output into a clean text block. Loops over the reviews array and formats each as , joined by double newlines. Also retrieves the original URL from the sheet node. Sentiment Analyzer (Uses Google Gemini Chat Model — API Key auth) — Analyzes the sentiment of the combined review text. The node is configured to read input from . Output includes a object with a (e.g. "positive", "negative", "neutral"). Google Gemini Chat Model (API Key auth — Google AI) — Provides the underlying language model for both the Sentiment Analyzer and Summarize Reviews nodes. Requires a valid Google AI API key. Summarize Reviews (Uses Google Gemini Chat Model — API Key auth) — Generates a concise summary of all reviews for the product using the Gemini model. The summary text is passed to the Telegram alert. Alert Group (API Key auth — Telegram Bot) — Sends a Telegram message to the chat ID (you must replace with your own chat ID). The message includes the date, sentiment category, product URL, and the generated summary. This acts as an alert (especially for negative sentiment, though all sentiments are sent). Store to Sheet (OAuth2 — Google Sheets) — Appends a new row to the sheet "user review aggregations" in the document "decodo". Columns stored: Url, Sentiment, and List Review (the cleaned review text). This builds a historical review database. Setup Instructions Google Sheets — Create two sheets in a Google Spreadsheet: one named "list urls" (with product URLs in column A) and another named "user review aggregations" (will be auto-populated). Grant n8n access via OAuth2 (Google account). Decodo — Sign up for a Decodo account and obtain an API key. Add the credentials in n8n under "Decodo API". Google Gemini — Enable the Generative Language API in Google Cloud, create an API key, and store it as a credential in n8n (type "Google AI"). Telegram — Create a bot via BotFather, get the bot token, and store it as a Telegram credential. Find your chat ID (e.g. by sending a message to @userinfobot) and update the field in the Alert Group node. Schedule — Adjust the Schedule Trigger to your preferred time (e.g. daily at 9 AM) by modifying the rule interval. Use Cases and Variations Multi-marketplace support — Replace Decodo with other review-scraping nodes (e.g. for eBay, Etsy) or use HTTP Request nodes with APIs. Slack instead of Telegram — Swap the Telegram node for a Slack node to send alerts to a channel. Advanced classification — Add a node to classify reviews by category (e.g., packaging, quality) using a custom prompt. Language translation — Insert a translation node before summarization to handle non-English reviews. Dashboard integration — Connect the output sheet to a BI tool like Google Data Studio for visual analytics.

15 nodes

AI-Powered CV Scanner with Google Sheets & Gemini

Overview This workflow automates the initial screening of job applicants by combining a web form, AI-powered CV analysis, and Google Sheets. When a candidate submits their application (name, email, and CV PDF), the workflow instantly extracts the text from the PDF using Mistral OCR, then sends it to Google Gemini for evaluation against a predefined job description. The AI returns a qualification score (0.0 to 1.0) and a detailed explanation, which are then logged alongside the candidate's details in a Google Sheet. This eliminates manual CV review, speeds up your hiring pipeline, and ensures every applicant is evaluated consistently. Workflow Steps Application Form (Form Trigger) — No auth required. This node presents a custom-branded web form to collect the candidate's Full Name, Email, and CV (PDF upload). The form is styled with a dark, glassmorphism theme and includes animated backgrounds. Once submitted, the workflow triggers automatically. Log Candidate Submission (Google Sheets) — OAuth2. Immediately after form submission, this node appends the candidate's name and email to the 'CVs' Google Sheet. This ensures the application is recorded even if the subsequent analysis steps fail. Extract CV Text (Mistral AI) — API Key auth. This node takes the uploaded PDF file from the form and uses Mistral's OCR API to extract all text content from the CV. It dynamically selects the binary file uploaded in the previous step. AI Qualification (LLM Chain) — This is the core analysis node. It uses a detailed prompt that includes: - A system message defining the AI as a professional, objective hiring assistant. - The full job description for a "Senior Frontend Developer" with core requirements and preferred qualifications. - Clear evaluation logic: candidates missing core requirements cannot score above 0.6; meeting all core requirements yields at least 0.75; preferred qualifications add bonuses up to 1.0. - The extracted CV text as context. - An instruction to output raw JSON only. Gemini 2.5 Flash Lite (Language Model) — API Key auth (Google AI Studio). This node provides the actual AI model (Google Gemini 2.5 Flash Lite) with a temperature of 0.4 for balanced, deterministic outputs. It powers the LLM Chain above. JSON Output Parser (Output Parser) — This node ensures the AI's response is valid JSON with the exact schema: (number) and (string). It prevents malformed responses from breaking downstream nodes. Add CV Analysis (Google Sheets) — OAuth2. After analysis, this node updates the candidate's row in the 'CVs' sheet by matching on the Email column. It writes the and from the AI's output into the corresponding columns. Create 'CVs' Spreadsheet (Google Sheets) — OAuth2. This node runs once when the workflow is first triggered manually. It creates a new Google Sheet named 'CVs' with columns: FullName, Email, QualificationRate, QualificationDescription. Setup Instructions Prerequisites A Google account (for Google Sheets) A Mistral AI account (free tier available) — Get your API key here A Google AI Studio account — Create an API key here Step-by-Step Google Sheets Credentials: In the three Google Sheets nodes, create or select an OAuth2 credential for Google Sheets. Grant access to create and edit spreadsheets. Mistral AI Credential: In the "Extract CV Text" node, create a new credential and paste your Mistral API key. Gemini Credential: In the "Gemini 2.5 Flash Lite" node, create a new credential and paste your Google AI Studio API key. Customize Job Description: Open the "AI Qualification" node and edit the section in the prompt to match your actual job posting. Activate the Workflow: Toggle the workflow to "Active" status. The "Application Form" node will generate a public URL you can share with candidates. Test: Use the "Start Here" manual trigger to initialize the Google Sheet, then submit a test application via the form URL. Use Cases & Variations Custom Job Roles: Replace the Senior Frontend Developer description with any role (e.g., Marketing Manager, Data Scientist, Sales Rep) by editing the prompt in the AI Qualification node. Different Storage: Replace Google Sheets with Airtable, Notion, or a database like PostgreSQL for storing applications and results. Multi-Round Screening: Add a Slack or email notification node to alert the hiring team when a candidate scores above a certain threshold (e.g., >0.8). Interview Scheduling: Connect the output to a Calendly or Google Calendar node to automatically invite high-scoring candidates for an interview. Batch Processing: Modify the trigger to accept a CSV upload of multiple CVs for bulk analysis. Enhanced Analysis: Add more output fields like "years of experience", "top skills", or "red flags" by updating the JSON schema in the Output Parser and the prompt.

18 nodes

Ready to automate with n8n?

Get affordable managed n8n hosting with 24/7 support.