Back to Integrations
integrationGoogle Drive node
integrationPostgres node

Google Drive and Postgres integration

Save yourself the work of writing custom integrations for Google Drive and Postgres and use n8n instead. Build adaptable and scalable Data & Storage, and Development workflows that work with your technology stack. All within a building experience you will love.

How to connect Google Drive and Postgres

  • Step 1: Create a new workflow
  • Step 2: Add and configure nodes
  • Step 3: Connect
  • Step 4: Customize and extend your integration
  • Step 5: Test and activate your workflow

Step 1: Create a new workflow and add the first step

In n8n, click the "Add workflow" button in the Workflows tab to create a new workflow. Add the starting point – a trigger on when your workflow should run: an app event, a schedule, a webhook call, another workflow, an AI chat, or a manual trigger. Sometimes, the HTTP Request node might already serve as your starting point.

Google Drive and Postgres integration: Create a new workflow and add the first step

Step 2: Add and configure Google Drive and Postgres nodes

You can find Google Drive and Postgres in the nodes panel. Drag them onto your workflow canvas, selecting their actions. Click each node, choose a credential, and authenticate to grant n8n access. Configure Google Drive and Postgres nodes one by one: input data on the left, parameters in the middle, and output data on the right.

Google Drive and Postgres integration: Add and configure Google Drive and Postgres nodes

Step 3: Connect Google Drive and Postgres

A connection establishes a link between Google Drive and Postgres (or vice versa) to route data through the workflow. Data flows from the output of one node to the input of another. You can have single or multiple connections for each node.

Google Drive and Postgres integration: Connect Google Drive and Postgres

Step 4: Customize and extend your Google Drive and Postgres integration

Use n8n's core nodes such as If, Split Out, Merge, and others to transform and manipulate data. Write custom JavaScript or Python in the Code node and run it as a step in your workflow. Connect Google Drive and Postgres with any of n8n’s 1000+ integrations, and incorporate advanced AI logic into your workflows.

Google Drive and Postgres integration: Customize and extend your Google Drive and Postgres integration

Step 5: Test and activate your Google Drive and Postgres workflow

Save and run the workflow to see if everything works as expected. Based on your configuration, data should flow from Google Drive to Postgres or vice versa. Easily debug your workflow: you can check past executions to isolate and fix the mistake. Once you've tested everything, make sure to save your workflow and activate it.

Google Drive and Postgres integration: Test and activate your Google Drive and Postgres workflow

Query Google Sheets/CSV data through an AI agent using PostgreSQL

Want to see it in action? Watch the full breakdown here: 📺 Video Link

Template Description
This n8n workflow empowers you to query structured financial data from Google Sheets or CSV files using AI-generated SQL. Unlike traditional vector database solutions that falter with numerical queries, this template leverages PostgreSQL for efficient data storage and an AI agent to dynamically create optimized SQL queries from natural language inputs.

What It Does
Retrieves data from Google Sheets or CSV files
Infers the data schema and builds a PostgreSQL table
Populates the table with your data
Uses an AI agent to translate natural language questions into SQL queries
Returns precise numerical results quickly and efficiently

Why Use This?
No SQL knowledge required—the AI generates queries for you
Bypasses the inefficiencies and costs of vector database approaches
Scales effortlessly without overwhelming the language model
Fully free and open-source

Setup Requirements

Pre-Conditions
PostgreSQL Database**: A running PostgreSQL instance (no specific extensions required beyond standard installation).
Google Sheets Access**: A publicly accessible or shared Google Sheet URL with structured data (e.g., financial records). Need a starting point? Use this Sample Google Sheet Template.
n8n Instance**: A working n8n setup with access to the Google Drive and PostgreSQL nodes.

Step-by-Step Instructions
Add Your Google Sheets URL
Open the "Google Drive Trigger" node.
Replace the placeholder URL with your Google Sheet’s link.
Verify the sheet name matches your data source.

Configure PostgreSQL
Update the "PostgreSQL" nodes with your database credentials (host, database, user, password).
The workflow automatically creates and populates the table based on your data schema.

Run the Workflow
Execute the workflow manually to set up the database.
Once initialized, use the AI agent by asking questions like:
"How much did I sell last week?"
"What were the total sales for Product X in February?"

(Optional) Automate Updates
Add a "Schedule Trigger" node to sync your Google Sheets data with PostgreSQL on a regular basis.

How It Works
Schema Detection**: The workflow analyzes your Google Sheets or CSV data to infer its structure and create an appropriate PostgreSQL table.
AI-Powered Queries**: An optimized AI agent converts your natural language questions into precise SQL queries, ensuring accurate results.
Efficient Retrieval**: By using PostgreSQL instead of vector-based methods, this template avoids common pitfalls like slow performance or inaccurate numerical outputs.

Tips for Success
Ensure your Google Sheet or CSV has consistent column headers for smooth schema detection.
Test with simple questions first to verify the AI agent’s query generation.
Check out the n8n Template Submission Guidelines for more best practices.

Nodes used in this workflow

Popular Google Drive and Postgres workflows

+6

Interactive Knowledge Base Chat with Supabase RAG using AI 📚💬

Google Drive File Ingestion to Supabase for Knowledge Base 📂💾 Overview 🌟 This n8n workflow automates the process of ingesting files from Google Drive into a Supabase database, preparing them for a knowledge base system. It supports text-based files (PDF, DOCX, TXT, etc.) and tabular data (XLSX, CSV, Google Sheets), extracting content, generating embeddings, and storing data in structured tables. This is a foundational workflow for building a company knowledge base that can be queried via a chat interface (e.g., using a RAG workflow). 🚀 Problem Solved 🎯 Manually managing a knowledge base with files from Google Drive is time-consuming and error-prone. This workflow solves that by: Automatically ingesting files from Google Drive as they are created or updated. Extracting content** from various file types (text and tabular). Generating embeddings for text-based files to enable vector search. Storing data in Supabase for efficient retrieval. Handling duplicates and errors to ensure data consistency. Target Audience: Knowledge Managers**: Build a centralized knowledge base from company files. Data Teams**: Automate the ingestion of spreadsheets and documents. Developers**: Integrate with other workflows (e.g., RAG for querying the knowledge base). Workflow Description 🔍 This workflow listens for new or updated files in Google Drive, processes them based on their type, and stores the extracted data in Supabase tables for later retrieval. Here’s how it works: File Detection: Triggers when a file is created or updated in Google Drive. File Processing: Loops through each file, extracts metadata, and validates the file type. Duplicate Check: Ensures the file hasn’t been processed before. Content Extraction: Text-based Files: Downloads the file, extracts text, splits it into chunks, generates embeddings, and stores the chunks in Supabase. Tabular Files: Extracts data from spreadsheets and stores it as rows in Supabase. Metadata Storage: Stores file metadata and basic info in Supabase tables. Error Handling: Logs errors for unsupported formats or duplicates. Nodes Breakdown 🛠️ Detect New File 🔔 Type**: Google Drive Trigger Purpose**: Triggers the workflow when a new file is created in Google Drive. Configuration**: Credential: Google Drive OAuth2 Event: File Created Customization**: Specify a folder to monitor specific directories. Detect Updated File 🔔 Type**: Google Drive Trigger Purpose**: Triggers the workflow when a file is updated in Google Drive. Configuration**: Credential: Google Drive OAuth2 Event: File Updated Customization**: Currently disconnected; reconnect if updates need to be processed. Process Each File 🔄 Type**: Loop Over Items Purpose**: Processes each file individually from the Google Drive trigger. Configuration**: Input: {{ $json.files }} Customization**: Adjust the batch size if processing multiple files at once. Extract File Metadata 🆔 Type**: Set Purpose**: Extracts metadata like file_id, file_name, mime_type, and web_view_link. Configuration**: Fields: file_id: {{ $json.id }} file_name: {{ $json.name }} mime_type: {{ $json.mimeType }} web_view_link: {{ $json.webViewLink }} Customization**: Add more metadata fields if needed (e.g., size, createdTime). Check File Type ✅ Type**: IF Purpose**: Validates the file type by checking the MIME type. Configuration**: Condition: mime_type contains supported types (e.g., application/pdf, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet). Customization**: Add more supported MIME types as needed. Find Duplicates 🔍 Type**: Supabase Purpose**: Checks if the file has already been processed by querying knowledge_base. Configuration**: Operation: Select Table: knowledge_base Filter: file_id = {{ $node['Extract File Metadata'].json.file_id }} Customization**: Add additional duplicate checks (e.g., by file name). Handle Duplicates 🔄 Type**: IF Purpose**: Routes the workflow based on whether a duplicate is found. Configuration**: Condition: {{ $node['Find Duplicates'].json.length > 0 }} Customization**: Add notifications for duplicates if desired. Remove Old Text Data 🗑️ Type**: Supabase Purpose**: Deletes old text data from documents if the file is a duplicate. Configuration**: Operation: Delete Table: documents Filter: metadata->>'file_id' = {{ $node['Extract File Metadata'].json.file_id }} Customization**: Add logging before deletion. Remove Old Data 🗑️ Type**: Supabase Purpose**: Deletes old tabular data from document_rows if the file is a duplicate. Configuration**: Operation: Delete Table: document_rows Filter: dataset_id = {{ $node['Extract File Metadata'].json.file_id }} Customization**: Add logging before deletion. Route by File Type 🔀 Type**: Switch Purpose**: Routes the workflow based on the file’s MIME type (text-based or tabular). Configuration**: Rules: Based on mime_type (e.g., application/pdf for text, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet for tabular). Customization**: Add more routes for additional file types. Download File Content 📥 Type**: Google Drive Purpose**: Downloads the file content for text-based files. Configuration**: Credential: Google Drive OAuth2 File ID: {{ $node['Extract File Metadata'].json.file_id }} Customization**: Add error handling for download failures. Extract PDF Text 📜 Type**: Extract from File (PDF) Purpose**: Extracts text from PDF files. Configuration**: File Content: {{ $node['Download File Content'].binary.data }} Customization**: Adjust extraction settings for better accuracy. Extract DOCX Text 📜 Type**: Extract from File (DOCX) Purpose**: Extracts text from DOCX files. Configuration**: File Content: {{ $node['Download File Content'].binary.data }} Customization**: Add support for other text formats (e.g., TXT, RTF). Extract XLSX Data 📊 Type**: Extract from File (XLSX) Purpose**: Extracts tabular data from XLSX files. Configuration**: File ID: {{ $node['Extract File Metadata'].json.file_id }} Customization**: Add support for CSV or Google Sheets. Split Text into Chunks ✂️ Type**: Text Splitter Purpose**: Splits extracted text into manageable chunks for embedding. Configuration**: Chunk Size: 1000 Chunk Overlap: 200 Customization**: Adjust chunk size and overlap based on document length. Generate Text Embeddings 🌐 Type**: OpenAI Purpose**: Generates embeddings for text chunks using OpenAI. Configuration**: Credential: OpenAI API key Operation: Embedding Model: text-embedding-ada-002 Customization**: Switch to a different embedding model if needed. Store Text in Supabase 💾 Type**: Supabase Vector Store Purpose**: Stores text chunks and embeddings in the documents table. Configuration**: Credential: Supabase credentials Operation: Insert Documents Table Name: documents Customization**: Add metadata fields to store additional context. Store Tabular Data 💾 Type**: Supabase Purpose**: Stores tabular data in the document_rows table. Configuration**: Operation: Insert Table: document_rows Columns: dataset_id, row_data Customization**: Add validation for tabular data structure. Store File Metadata 📋 Type**: Supabase Purpose**: Stores file metadata in the document_metadata table. Configuration**: Operation: Insert Table: document_metadata Columns: file_id, file_name, file_type, file_url Customization**: Add more metadata fields as needed. Record in Knowledge Base 📚 Type**: Supabase Purpose**: Stores basic file info in the knowledge_base table. Configuration**: Operation: Insert Table: knowledge_base Columns: file_id, file_name, file_type, file_url, upload_date Customization**: Add indexes for faster lookups. Log File Errors ⚠️ Type**: Supabase Purpose**: Logs errors for unsupported file types. Configuration**: Operation: Insert Table: error_log Columns: error_type, error_message Customization**: Add notifications for errors. Log Duplicate Errors ⚠️ Type**: Supabase Purpose**: Logs errors for duplicate files. Configuration**: Operation: Insert Table: error_log Columns: error_type, error_message Customization**: Add notifications for duplicates. Interactive Knowledge Base Chat with Supabase RAG using GPT-4o-mini 📚💬 Introduction 🌟 This n8n workflow creates an interactive chat interface that allows users to query a company knowledge base using Retrieval-Augmented Generation (RAG). It retrieves relevant information from text documents and tabular data stored in Supabase, then generates natural language responses using OpenAI’s GPT-4o-mini model. Designed for teams managing internal knowledge, this workflow enables users to ask questions like “What’s the remote work policy?” or “Show me the latest budget data” and receive accurate, context-aware responses in a conversational format. 🚀 Problem Statement 🎯 Managing a company knowledge base can be a daunting task—employees often struggle to find specific information buried in documents or spreadsheets, leading to wasted time and inefficiencies. Traditional search methods may not understand natural language queries or provide contextually relevant results. This workflow solves these issues by: Offering a chat-based interface for natural language queries, making it easy for users to ask questions in their own words. Leveraging RAG to retrieve relevant text and tabular data from Supabase, ensuring responses are accurate and context-aware. Supporting diverse file types, including text-based files (e.g., PDFs, DOCX) and tabular data (e.g., XLSX, CSV), for comprehensive knowledge access. Maintaining conversation history to provide context during interactions, improving the user experience. Target Audience 👥 This workflow is ideal for: HR Teams**: Quickly access company policies, employee handbooks, or benefits documents. Finance Teams**: Retrieve budget data, expense reports, or financial summaries from spreadsheets. Knowledge Managers**: Build a centralized assistant for internal documentation, streamlining information access. Developers**: Extend the workflow with additional tools or integrations for custom use cases. Workflow Description 🔍 This workflow consists of a chat interface powered by n8n’s Chat Trigger node, an AI Agent node for RAG, and several tools to retrieve data from Supabase. Here’s how it works step-by-step: User Initiates a Chat: The user interacts with a chat interface, sending queries like “Summarize our remote work policy” or “Show budget data for Q1 2025.” Query Processing with RAG: The AI Agent processes the query using RAG, retrieving relevant data from Supabase tables and generating a response with OpenAI’s GPT-4o-mini model. Data Retrieval and Response Generation: The workflow uses multiple tools to fetch data: Retrieves text chunks from the documents table using vector search. Fetches tabular data from the document_rows table based on file IDs. Extracts full document text or lists available files as needed. Generates a natural language response combining the retrieved data. Conversation History Management: Stores the conversation history in Supabase to maintain context for follow-up questions. Response Delivery: Formats and sends the response back to the chat interface for the user to view. Nodes Breakdown 🛠️ Start Chat Interface 💬 Type**: Chat Trigger Purpose**: Provides the interactive chat interface for users to input queries and receive responses. Configuration**: Chat Title: Company Knowledge Base Assistant Chat Subtitle: Ask me anything about company documents! Welcome Message: Hello! I’m your Company Knowledge Base Assistant. How can I help you today? Suggestions: What is the company policy on remote work?, Show me the latest budget data., List all policy documents. Output Chat Session ID: true Output User Message: true Customization**: Update the title and welcome message to align with your company branding (e.g., HR Knowledge Assistant). Add more suggestions relevant to your use case (e.g., What are the company benefits?). Process Query with RAG 🧠 Type**: AI Agent Purpose**: Orchestrates the RAG process by retrieving relevant data using tools and generating responses with OpenAI’s GPT-4o-mini. Configuration**: Credential: OpenAI API key Model: gpt-4o-mini System Prompt: You are a helpful assistant for a company knowledge base. Use the provided tools to retrieve relevant information from documents and tabular data. If the query involves tabular data, format it clearly in your response. If no relevant data is found, respond with "I couldn’t find any relevant information. Can you provide more details?" Input Field: {{ $node['Start Chat Interface'].json.message }} Customization**: Switch to a different model (e.g., gpt-3.5-turbo) to adjust cost or performance. Modify the system prompt to change the tone (e.g., more formal for HR use cases). Retrieve Text Chunks 📄 Type**: Supabase Vector Store (Tool) Purpose**: Retrieves relevant text chunks from the documents table using vector search. Configuration**: Credential: Supabase credentials Operation Mode: Retrieve Documents (As Tool for AI Agent) Table Name: documents Embedding Field: embedding Content Field: content_text Metadata Field: metadata Embedding Model: OpenAI text-embedding-ada-002 Top K: 10 Customization**: Adjust Top K to retrieve more or fewer results (e.g., 5 for faster responses). Ensure the match_documents function (see prerequisites) is defined in Supabase. Fetch Tabular Data 📊 Type**: Supabase (Tool, Execute Query) Purpose**: Retrieves tabular data from the document_rows table based on a file ID. Configuration**: Credential: Supabase credentials Operation: Execute Query Query: SELECT row_data FROM document_rows WHERE dataset_id = $1 LIMIT 10 Tool Description: Run a SQL query - use this to query from the document_rows table once you know the file ID you are querying. dataset_id is the file_id and you are always using the row_data for filtering, which is a jsonb field that has all the keys from the file schema given in the document_metadata table. Customization**: Modify the query to filter specific columns or add conditions (e.g., WHERE dataset_id = $1 AND row_data->>'year' = '2025'). Increase the LIMIT for larger datasets. Extract Full Document Text 📜 Type**: Supabase (Tool, Execute Query) Purpose**: Fetches the full text of a document by concatenating all text chunks for a given file_id. Configuration**: Credential: Supabase credentials Operation: Execute Query Query: SELECT string_agg(content_text, ' ') as document_text FROM documents WHERE metadata->>'file_id' = $1 GROUP BY metadata->>'file_id' Tool Description: Given file id fetch the text from the documents Customization**: Add filters to the query if needed (e.g., limit to specific metadata fields). List Available Files 📋 Type**: Supabase (Tool, Select) Purpose**: Lists all files in the knowledge base from the document_metadata table. Configuration**: Credential: Supabase credentials Operation: Select Schema: public Table: document_metadata Tool Description: Use this tool to fetch all documents including the table schema if the file is csv, excel or xlsx Customization**: Add filters to list specific file types (e.g., WHERE file_type = 'application/pdf'). Modify the columns selected to include additional metadata (e.g., file_size). Manage Chat History 💾 Type**: Postgres Chat Memory (Tool) Purpose**: Stores and retrieves conversation history to maintain context. Configuration**: Credential: Supabase credentials (Postgres-compatible) Table Name: n8n_chat_history Session ID Field: session_id Session ID Value: {{ $node['Start Chat Interface'].json.sessionId }} Message Field: message Sender Field: sender Timestamp Field: timestamp Context Window Length: 5 Customization**: Increase the context window length for longer conversations (e.g., 10 messages). Add indexes on session_id and timestamp in Supabase for better performance. Format and Send Response 📤 Type**: Set Purpose**: Formats the AI Agent’s response and sends it back to the chat interface. Configuration**: Fields: response: {{ $node['Process Query with RAG'].json.output }} Customization**: Add additional formatting to the response if needed (e.g., prepend with a timestamp or apply markdown formatting). Setup Instructions 🛠️ Prerequisites 📋 n8n Setup: Ensure you’re using n8n version 1.0 or higher. Enable the AI features in n8n settings. Supabase: Create a Supabase project and set up the following tables: documents: id (uuid), content_text (text), embedding (vector(1536)), metadata (jsonb) document_rows: id (uuid), dataset_id (varchar), row_data (jsonb) document_metadata: file_id (varchar), file_name (varchar), file_type (varchar), file_url (text) knowledge_base: id (serial), file_id (varchar), file_name (varchar), file_type (varchar), file_url (text), upload_date (timestamp) n8n_chat_history: id (serial), session_id (varchar), message (text), sender (varchar), timestamp (timestamp) Add the match_documents function to Supabase to enable vector search: CREATE OR REPLACE FUNCTION match_documents ( query_embedding vector(1536), match_count int DEFAULT 5, filter jsonb DEFAULT '{}' ) RETURNS TABLE ( id uuid, content_text text, metadata jsonb, similarity float ) LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY SELECT documents.id, documents.content_text, documents.metadata, 1 - (documents.embedding <=> query_embedding) as similarity FROM documents WHERE documents.metadata @> filter ORDER BY similarity DESC LIMIT match_count; END; $$;

Automated Document Sync Between SharePoint and Google Drive with Supabase

SharePoint → Supabase → Google Drive Sync Workflow Overview This workflow is a multi-system document synchronization pipeline built in n8n, designed to automatically sync and back up files between Microsoft SharePoint, Supabase/Postgres, and Google Drive. It runs on a scheduled trigger, compares SharePoint file metadata against your Supabase table, downloads new or updated files, uploads them to Google Drive, and marks records as completed — keeping your databases and storage systems perfectly in sync. Workflow Structure Data Source:** SharePoint REST API for recursive folder and file discovery. Processing Layer:** n8n logic for filtering, comparison, and metadata normalization. Destination Systems:** Supabase/Postgres for metadata, Google Drive for file backup. SharePoint Sync Flow (Frontend Flow) Trigger:** Schedule Trigger Runs at fixed intervals (customizable) to start synchronization. Fetch Files:** Microsoft SharePoint HTTP Request Recursively retrieves folders and files using SharePoint’s REST API: /GetFolderByServerRelativeUrl(...)?$expand=Files,Folders,Folders/Files,Folders/Folders/Folders/Files Filter Files:** filter files A Code node that flattens nested folders and filters unwanted file types: Excludes system or temporary files (~$) Excludes extensions: .db, .msg, .xlsx, .xlsm, .pptx Normalize Metadata:** normalize last modified date Ensures consistent Last_modified_date format for accurate comparison. Fetch Existing Records:** Supabase (Get) Retrieves current entries from n8n_metadata to compare against SharePoint files. Compare Datasets:** Compare Datasets Detects new or modified files based on UniqueId, Last_modified_date, and Exists. Routes only changed entries forward for processing. File Processing Engine (Backend Flow) Loop:** Loop Over Items2 Iterates through each new or updated file detected. Build Metadata:** get metadata and Set metadata Constructs final metadata fields: file_id, file_title, file_url, file_type, foldername, last_modified_date Generates fileUrl using UniqueId and ServerRelativeUrl if missing. Upsert Metadata:** Insert Document Metadata Inserts or updates file records in Supabase/Postgres (n8n_metadata table). Operation: upsert with id as the primary matching key. Download File:** Microsoft SharePoint HTTP Request1 Fetches the binary file directly from SharePoint using its ServerRelativeUrl. Rename File:** rename files Renames each downloaded binary file to its original file_title before upload. Upload File:** Upload file Uploads the renamed file to Google Drive (My Drive → root folder). Mark Complete:** Postgres Updates the Supabase/Postgres record setting Loading Done = true. Optional Cleanup:** Supabase1 Deletes obsolete or invalid metadata entries when required. Integrations Used | Service | Purpose | Credential | |----------|----------|-------------| | Microsoft SharePoint | File retrieval and download | microsoftSharePointOAuth2Api | | Supabase / Postgres | Metadata storage and synchronization | Supabase account 6 ayan | | Google Drive | File backup and redundancy | Google Drive account 6 rn dbt | | n8n Core | Flow control, dataset comparison, batch looping | Native | System Prompt Summary > “You are a SharePoint document synchronization workflow. Fetch all files, compare them to database entries, and only process new or modified files. Download files, rename correctly, upload to Google Drive, and mark as completed in Supabase.” Workflow rule summary: > “Maintain data integrity, prevent duplicates, handle retries gracefully, and continue on errors. Skip excluded file types and ensure reliable backups between all connected systems.” Key Features Scheduled automatic sync across SharePoint, Supabase, and Google Drive Intelligent comparison to detect only new or modified files Idempotent upsert for consistent metadata updates Configurable file exclusion filters Safe rename + upload pipeline for clean backups Error-tolerant and fully automated operation Summary > A reliable, SharePoint-to-Google Drive synchronization workflow built with n8n, integrating Supabase/Postgres for metadata management. It automates file fetching, filtering, downloading, uploading, and marking as completed — ensuring your data stays mirrored across platforms. Perfect for enterprises managing document automation, backup systems, or cross-cloud data synchronization. Need Help or More Workflows? Want to customize this workflow for your organization? Our team at Digital Biz Tech can extend it for enterprise-scale document automation, RAGs and social media automation. We can help you set it up for free — from connecting credentials to deploying it live. Contact: [email protected] Website: https://www.digitalbiz.tech LinkedIn: https://www.linkedin.com/company/digital-biz-tech/ You can also DM us on LinkedIn for any help.

Query Google Sheets/CSV data through an AI Agent using PostgreSQL

Want to see it in action? Watch the full breakdown here: 📺 Video Link Template Description This n8n workflow empowers you to query structured financial data from Google Sheets or CSV files using AI-generated SQL. Unlike traditional vector database solutions that falter with numerical queries, this template leverages PostgreSQL for efficient data storage and an AI agent to dynamically create optimized SQL queries from natural language inputs. What It Does Retrieves data from Google Sheets or CSV files Infers the data schema and builds a PostgreSQL table Populates the table with your data Uses an AI agent to translate natural language questions into SQL queries Returns precise numerical results quickly and efficiently Why Use This? No SQL knowledge required—the AI generates queries for you Bypasses the inefficiencies and costs of vector database approaches Scales effortlessly without overwhelming the language model Fully free and open-source Setup Requirements Pre-Conditions PostgreSQL Database**: A running PostgreSQL instance (no specific extensions required beyond standard installation). Google Sheets Access**: A publicly accessible or shared Google Sheet URL with structured data (e.g., financial records). Need a starting point? Use this Sample Google Sheet Template. n8n Instance**: A working n8n setup with access to the Google Drive and PostgreSQL nodes. Step-by-Step Instructions Add Your Google Sheets URL Open the "Google Drive Trigger" node. Replace the placeholder URL with your Google Sheet’s link. Verify the sheet name matches your data source. Configure PostgreSQL Update the "PostgreSQL" nodes with your database credentials (host, database, user, password). The workflow automatically creates and populates the table based on your data schema. Run the Workflow Execute the workflow manually to set up the database. Once initialized, use the AI agent by asking questions like: "How much did I sell last week?" "What were the total sales for Product X in February?" (Optional) Automate Updates Add a "Schedule Trigger" node to sync your Google Sheets data with PostgreSQL on a regular basis. How It Works Schema Detection**: The workflow analyzes your Google Sheets or CSV data to infer its structure and create an appropriate PostgreSQL table. AI-Powered Queries**: An optimized AI agent converts your natural language questions into precise SQL queries, ensuring accurate results. Efficient Retrieval**: By using PostgreSQL instead of vector-based methods, this template avoids common pitfalls like slow performance or inaccurate numerical outputs. Tips for Success Ensure your Google Sheet or CSV has consistent column headers for smooth schema detection. Test with simple questions first to verify the AI agent’s query generation. Check out the n8n Template Submission Guidelines for more best practices.
+18

💅 AI Agents Generate Content & Automate Posting for Beauty Salon Social Media 📲

💅 AI Agents Generate Content & Automate Posting for Beauty Salon Social Media 📲 Who Is This For? This workflow is for beauty salons who want consistent, high‑quality social media content without writing every post manually. It also suits agencies and automation builders who manage multiple beauty brands and want a reusable, AI‑driven posting system they can adapt per client. What Problem Is This Workflow Solving? Many beauty businesses struggle to post regularly because research, copywriting, and design all take time and marketing skills. This workflow automates research, writing, image creation, and posting, so your channels stay active and relevant while you focus on clients and services. What This Workflow Does Generates short, engaging posts tailored to a beauty‑salon audience (hair, nails, skincare, make‑up, self‑care) using an AI agent. Uses Tavily Internet Search to pull up‑to‑date information and trends based on a reference link or topic. Turns each post into a detailed, photorealistic image prompt and creates a matching visual with an AI image model (for example, gpt‑image‑1 or other connected providers). Automatically sends the final text and image to Telegram, and can be extended to other social platforms from the Split Out node. How It Works Trigger the workflow Scheduled automatic generation:** Run the parent workflow on a schedule (for example, once per day at 9 AM) to publish new content regularly. Google Sheets trigger:** Generate content when a new row with a reference link or topic is added to your sheet. Use it when you manage ideas or briefs in Google Sheets and want the workflow to react as soon as a new idea appears. RSS Feed trigger:** Start the workflow when new items appear in a selected RSS feed. Ideal for turning fresh blog posts, news, or industry updates into social media content or automated summaries. Meta (Facebook/Instagram) webhook:** Use the Meta Reference trigger to fire the workflow on incoming webhooks from Meta (for example, new comments, messages, or events). Helpful when you want to auto‑respond, log activity, or generate follow‑up content from Meta activity. Airtable trigger:** Start the workflow when records in a selected Airtable base/table change (for example, a new idea, brief, or status update), so your posts react instantly to updates in your Airtable content board. Postgres trigger:** Fire the workflow when new rows are inserted or existing rows are updated in a connected PostgreSQL table, letting you drive content generation from events in your app database or Supabase‑style back end. Manual start:* Hit Execute workflow* whenever you want to spin up a batch of posts on demand, test new prompt settings, or debug the flow step by step. Research and generate copy The GENERATE TEXT agent calls Tavily to gather fresh information on the topic. It writes a post under 1024 characters with a hook, practical tips, relevant hashtags, and a closing line with your salon address and contact. Create the visual The GENERATE PROMPT agent converts the post into a single, clear description of the scene (client, service, salon interior, lighting, mood) with a strict “no text on image” rule. An image model such as gpt‑image‑1 or one of the HTTP image APIs renders a matching beauty visual. Distribute the content The Split Out node fans out the result so Telegram receives a photo post with the generated caption. Additional social or content nodes (for example Facebook, LinkedIn, X, template tools) can be wired after this step for multi‑channel posting. How to Customize This Workflow to Your Needs Brand voice** Edit the system message in the GENERATE TEXT node to adjust tone (luxury, friendly, clinical, playful), language, services, and city. Update the final address and phone line to match your salon details. Topics and triggers** Point the Google Sheets Trigger to your own document ID, sheet, and columns for ideas, links, or campaign themes. Use the Schedule Trigger for fully automatic posting or rely on the Manual Trigger for controlled, batch generation sessions. Models and providers** Swap GPT‑5 llm and the default image model for alternatives such as Mistral, Gemini, Anthropic, DeepSeek, or custom HTTP image APIs by enabling the corresponding nodes and adding credentials. Channels and outputs** Connect or remove social nodes after Split Out depending on which platforms you actively use. Add extra processing steps (for example resizing images or adding UTM parameters) before each channel if needed. Visual style** Tweak the GENERATE PROMPT instructions to control composition (close‑up vs. full‑body), color palette, lighting, and overall salon aesthetic, while keeping the constraint of no text or logos in the image.
+6

Telegram AI Chatbot with Document-Based Answers using OpenAI and PGVector RAG

🤖 AI Q&A Chatbot Workflow – Build Your Own AI Agent Trained on Private Documents This powerful AI automation add-on upgrades your Telegram Bot Starter Template by integrating a fully functional AI chatbot and a context-aware AI agent that answers user questions using your internal documents. Unlike generic bots, this chatbot uses your own data to respond with deeply personalized, context-relevant information — perfect for support, onboarding, internal knowledge access, and client-facing interactions. It connects to any PostgreSQL database — including Neon.tech, Supabase, or a self-hosted Postgres setup — allowing you to build custom AI-powered FAQ assistants, internal support bots, or knowledge-based customer service tools. 🧠 Why It Works: Contextual Retrieval The secret is Contextual Retrieval — a powerful technique where your documents are stored in a way that preserves meaning and context. This allows the AI to fetch highly relevant, source-backed responses, eliminating hallucinations and guesswork. > Data is embedded, chunked, and saved in a vector database (Postgres + PGVector), enabling smart semantic search tailored to your needs. 📖 Learn more about this approach in this article by Anthropic → ✨ Key Features Chat with your internal documents**: Uses your content to answer questions with precision Built-in document vectorization**: Pre-configured Google Drive ingestion flow (Notion, Airtable, Dropbox available separately) Contextual memory**: Past chats stored in PostgreSQL for personalized conversations Plug-and-play architecture**: Connect Supabase, OpenAI, custom APIs via n8n’s interface 👤 Who Can Use This Workflow? Entrepreneurs & startups** building branded AI chatbots without code Customer support teams** automating answers using documentation Ops teams** creating internal FAQ bots for onboarding and training No-code developers** using n8n to build Telegram bots with AI features ⚙️ Setup Instructions You'll find step-by-step instructions inside the workflow. Quick Setup Overview: Import the workflow into n8n (cloud or self-hosted) Add your Telegram Bot credentials Connect your PostgreSQL DB (Neon, Supabase, etc.) Set up document ingestion from Google Drive Activate the workflow and start chatting 🧩 Extensibility This workflow is modular and ready to expand. Build powerful assistants by connecting additional workflows: Vectorization modules** for Notion, Airtable, Dropbox, and others Any vector DB**: Neon.tech, Supabase, or self-hosted PGVector ✍🏻 Telegram User Registration Module → 💵 Telegram Payment, Invoicing & Refund Module → 🧠 More Smart AI Agents Explore more AI workflows and agents on my Gumroad → 🌐 Agent: Find in the Internet — fetches live info from the web 📁 Agent: Search Internal Docs — queries Notion, Google Drive, etc. 📦 Agent: Check Order Status — reads status from Airtable or CRM 💰 Agent: Calculate Cost or Quote — builds pricing logic from inputs 📨 Submit your idea here for a custom AI agent →
+19

💾 Generate Blog Posts on Autopilot with GPT‑5, Tavily and WordPress

Who Is This For? This workflow is designed for marketers, content creators, agencies, and solo founders who want to publish long‑form posts with visuals on autopilot using n8n and AI agents. ​ Whether you run a blog, SaaS, personal brand, newsletter, or client accounts, this tool helps you keep a consistent content pipeline without manually writing every article, creating images, and posting to each platform one by one. ​ ​ 💪🏼 While the template is wired around classic blog + social media distribution, the underlying logic is universal. You can easily adapt it to any niche by editing prompts, swapping models, and re‑wiring nodes. You can plug in any LLM you like, from ChatGPT to Claude, Gemini, Mistral, DeepSeek, OpenRouter, or even local models through Ollama. ​ What Problem Is This Workflow Solving? 🤯 Most teams waste hours on the same repetitive loop: research a topic, gather links, write a blog post, craft social captions, generate visuals, upload everything to multiple platforms, and archive assets. ​ ​ 💎 This workflow solves that by automating the full content chain—from research and blog‑post generation to image creation, publishing across channels, and logging everything in your content database—so your feeds stay active while you focus on strategy, not busywork. ​ What This Workflow Does ✨ Generates in‑depth blog posts tailored to your topic and target audience, enriched with fresh references from the web via Tavily/SerpAPI search tools. ​ ✨ Creates an image prompt and title from the article, generates the visual with OpenAI Images (gpt-image-1), and converts it into a ready‑to‑use image file. ​ ✨ Automatically publishes content to your connected platforms (WordPress for blog posts, Telegram, X/Twitter, Facebook, LinkedIn) while saving images to Google Drive and logging each publication in Google Sheets for tracking. ​ How It Works? Surprisingly simple ☺️ The workflow is triggered by another n8n workflow or by one of several triggers (Facebook, RSS, Google Sheets, Airtable, Postgres) that pass in the blogTopic, targetAudience, and Telegram chatID. ​ ​ The Blog Post Agent (LLM with access to Tavily/SerpAPI) researches the topic, writes a structured article for the specified audience, and sends its output to the Image Prompt Agent, which turns the content into a visual prompt and title. ​ 🎯 The end result: you provide a topic, run the workflow, and receive a complete blog post, matching image, and ready‑made social posts shipped directly to your channels and archives—no manual copy‑paste. ​ How to Customize This Workflow to Your Needs 🎨 Switch AI models and fine‑tune prompts so the agent can handle your exact formats: tutorials, case studies, listicles, product updates, thought‑leadership pieces, or campaign landing posts. 🔍 Refine research sources inside Tavily/SerpAPI to prioritize the domains, blogs, and docs your audience trusts, keeping posts accurate and up to date. ⏰ Adjust posting cadence and schedules to align with peak engagement for your audience, mixing automated slots with manual “launch” runs for special announcements. 📱 Expand or trim channels as needed: keep just WordPress + LinkedIn, add Telegram as a content feed, or plug the workflow into additional automations like email campaigns or RSS feeds. 📊 Use Google Sheets as your content hub to store ideas, angles, CTAs, references, and performance notes so you can double‑down on topics and formats that perform best. 🎬 Swap images for video by replacing the image generation node with video tools (for example, Runway‑style APIs) if your strategy is video‑first while keeping the same prompt pipeline. 💾 Build a reusable prompt library in Sheets, Notion, or Airtable so you can rotate proven prompt patterns each month and keep quality high without reinventing the wheel. 🤖 The system will continuously generate blog posts, visuals, and social updates and publish them across your selected platforms while archiving everything in Drive and Sheets—keeping your brand visible, consistent, and professional with minimal ongoing effort.

Build your own Google Drive and Postgres integration

Create custom Google Drive and Postgres workflows by choosing triggers and actions. Nodes come with global operations and settings, as well as app-specific parameters that can be configured. You can also use the HTTP Request node to query data from any app or service with a REST API.

Google Drive supported actions

Copy
Create a copy of an existing file
Create From Text
Create a file from a provided text
Delete
Permanently delete a file
Download
Download a file
Move
Move a file to another folder
Share
Add sharing permissions to a file
Update
Update a file
Upload
Upload an existing file to Google Drive
Search
Search or list files and folders
Create
Create a folder
Delete
Permanently delete a folder
Share
Add sharing permissions to a folder
Create
Create a shared drive
Delete
Permanently delete a shared drive
Get
Get a shared drive
Get Many
Get the list of shared drives
Update
Update a shared drive

Postgres supported actions

Delete
Delete an entire table or rows in a table
Execute Query
Execute an SQL query
Insert
Insert rows in a table
Insert or Update
Insert or update rows in a table
Select
Select rows from a table
Update
Update rows in a table

FAQs

  • Can Google Drive connect with Postgres?

  • Can I use Google Drive’s API with n8n?

  • Can I use Postgres’s API with n8n?

  • Is n8n secure for integrating Google Drive and Postgres?

  • How to get started with Google Drive and Postgres integration in n8n.io?

Need help setting up your Google Drive and Postgres integration?

Discover our latest community's recommendations and join the discussions about Google Drive and Postgres integration.
Mikhail Savenkov
Honza Pav
hubschrauber
Jon
David O'Neil

Looking to integrate Google Drive and Postgres in your company?

Over 3000 companies switch to n8n every single week

Why use n8n to integrate Google Drive with Postgres

Build complex workflows, really fast

Build complex workflows, really fast

Handle branching, merging and iteration easily.
Pause your workflow to wait for external events.

Code when you need it, UI when you don't

Simple debugging

Your data is displayed alongside your settings, making edge cases easy to track down.

Use templates to get started fast

Use 1000+ workflow templates available from our core team and our community.

Reuse your work

Copy and paste, easily import and export workflows.

Implement complex processes faster with n8n

red iconyellow iconred iconyellow icon