AI-Powered PostgreSQL Data Analysis via Google Sheets RAG - n8n Workflow

Use this sophisticated n8n workflow to sync Google Sheets data to PostgreSQL, then query the database naturally using a Gemini AI Agent. Leverage powerful n8n templates for RAG.

Workflow Preview

Ready to automate?

Download this n8n workflow template and start using it instantly.

Who is this best for?


  • Data analysts and business users who need to ask complex questions about spreadsheet data without writing SQL.

  • Automation specialists looking for advanced n8n templates integrating RAG, LLMs, and custom data preparation logic.

  • Teams who require a reliable pipeline for syncing volatile spreadsheet data into a permanent, queryable database (PostgreSQL).

  • Developers seeking a powerful, extensible n8n workflow foundation for AI-driven data insights.

Overview

This advanced solution leverages the power of n8n to bridge the gap between structured spreadsheet data and intelligent AI analysis. It provides a robust, two-part system. The first part is a data pipeline that automatically detects changes via a Google Drive n8n trigger, pulls Google Sheets data, dynamically infers data types (handling complex values like currency, percentages, and various date formats) using a custom n8n node, and loads it into PostgreSQL for reliable storage. The second part—the conversational interface—is an AI Agent that uses specialized n8n templates and LangChain tools (powered by Google Gemini) to generate and execute complex SQL queries based on natural language input. This full-cycle n8n workflow transforms static data into a dynamic, conversational knowledge base, providing deep data insights without requiring manual SQL coding.

How it Works

This comprehensive n8n workflow consists of two major interconnected parts: Data Synchronization and AI Querying.

Part 1: Data Synchronization (Google Sheets to Postgres)


  1. Trigger: The process starts with the Google Drive n8n trigger monitoring a specific spreadsheet file for changes, ensuring the database always reflects the latest source data.

  2. Configuration: The changethis Set n8n node defines the target tableurl and sheetname.

  3. Schema Check: A PostgreSQL n8n node checks if the destination table (aitable...) already exists.

  4. Data Fetch and Refresh: The flow fetches all data via the Google Sheets n8n node. If the table exists, it's dropped by the remove table Postgres n8n node to ensure a clean refresh.

  5. Dynamic Schema Generation: The create table query Code n8n node performs crucial data type inference, detecting column types (Timestamp, Decimal for currency, Text) and generating a precise CREATE TABLE SQL query.

  6. Table Creation: The create table PostgreSQL n8n node executes the schema creation.

  7. Data Normalization: The create insertion query Code n8n node iterates through the sheet data, normalizing values (e.g., stripping currency symbols, converting dates to ISO format), and building a highly optimized, parameterized INSERT INTO query.

  8. Bulk Insertion: The perform insertion PostgreSQL n8n node executes the bulk data load.

Part 2: AI Querying (Natural Language to SQL)


  1. Conversation Start: The Manual Chat n8n trigger initiates the conversation, feeding the user's question into the Agent.

  2. Agent Orchestration: The AI Agent With SQL Query Prompt n8n node (LangChain Agent, powered by Google Gemini Chat Model) takes control.

  3. Schema Retrieval: The Agent first calls the getpostgresschema tool (a separate n8n workflow) to understand the current database structure.

  4. SQL Generation: Based on a detailed system prompt defining strict SQL generation rules, the Agent crafts the necessary PostgreSQL query.

  5. Query Execution: The Agent then uses the executequery_tool (another separate n8n workflow) to run the generated SQL query against the database.

  6. Response: The query results are returned to the Agent, which formats them into a clear, natural language answer for the user. This advanced n8n workflow ensures context-aware and accurate data retrieval.

Installation Guide

To deploy this RAG n8n workflow, you must import this JSON and set up two additional sub-workflows for the AI tools, as indicated by the sticky notes.

1. Import the Workflow

Import the provided JSON into your n8n instance.

2. Configure Credentials

Set up the following credentials:
Google Drive OAuth2 API: For the Google Drive n8n trigger.
Google Sheets OAuth2 API: To read the spreadsheet data.
PostgreSQL: For connecting to your database (used by the main sync path and the tool workflows).
Google Gemini API: For the LangChain Agent's LLM.

3. Setup Sub-Workflows

Create and save the following two workflows, ensuring they have the exact names specified:

A. queryexecuter Workflow
This workflow handles SQL execution.
The n8n trigger is Execute Workflow Trigger.
It connects to the sql query executor (Postgres n8n node, executing {{ $json.query.sql }}).
The result feeds into response output (Set n8n node) to return the data.

B. get database schema Workflow
This workflow retrieves schema information for the Agent.
The n8n trigger is Execute Workflow Trigger.
It connects to schema finder (Postgres n8n node, running the schema query).
The result is passed to schema to string (Code n8n node) to format the schema for the LLM.

4. Final Configuration

In the main workflow, ensure the Google Drive Trigger is watching the correct file ID.
Update the change
this n8n node with your spreadsheet URL and sheet name.

  • Ensure the queryexecuter and get database schema workflow IDs are correctly linked in the executequerytool and getpostgres_schema nodes respectively.

Node Details

Google Drive Trigger (n8n trigger): Starts the data synchronization process upon changes to a watched Google Sheet file.
Google Sheets (n8n node): Fetches all data rows from the specified sheet URL, preparing it for database migration.
Code Node (create table query): This highly customized n8n node analyzes sample data to infer data types, specifically identifying currency fields (e.g., '$', '₹') and date formats (MM/DD/YYYY). It generates the dynamic CREATE TABLE SQL command for PostgreSQL.
Code Node (create insertion query): Handles data cleansing and normalization. It converts messy spreadsheet data (like currency strings) into clean, ready-to-insert numeric or date values, generating a fast, parameterized INSERT INTO query.
Postgres (n8n node): Used throughout the n8n workflow for checking table existence, dropping tables, creating the new schema, and performing the bulk data insertion.
When chat message received (n8n trigger): The primary n8n trigger for the RAG component, starting the natural language query session.
Google Gemini Chat Model (LangChain n8n node): The large language model providing the reasoning capabilities for the agent to convert text into complex SQL.
AI Agent With SQL Query Prompt (LangChain n8n node): The core orchestration n8n node. It manages the conversation, utilizes the getpostgresschema and executequerytool n8n templates (via the tool workflow nodes) to gather information, construct the query, and deliver the final answer based on a detailed RAG prompt.

Related n8n Workflows

Free

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

I combine my full-stack development expertise with AI automation using n8n, creating scalable workflows and seamless integrations for smarter business solutions.

Featured*