Automate SQL Query Generation from Email Questions with n8n

This n8n workflow automates transforming natural language questions about emails into precise SQL queries against your email database schema. Save hours and reduce errors by automatically generating and executing SQL queries based on your questions.
postgres
agent
chatTrigger
+10
Workflow Identifier: 1647
NODES in Use: Set, ConvertToFile, ReadWriteFile, ExtractFromFile, ChatTrigger, StickyNote, ManualTrigger, If, Postgres, LMChatOllama, Merge, ExecuteWorkflowTrigger, Agent
Automate SQL queries with n8n and Postgres

Press CTRL+F5 if the workflow didn't load.

Learn how to Build this Workflow with AI:

What this workflow does

This workflow turns plain English questions about email data into exact SQL queries for a PostgreSQL database.
It helps users get the right answers from email metadata without writing SQL manually.
You ask a question, the AI writes a query, runs it, and shows you results fast.

This saves time and stops mistakes in manual query writing.


Who should use this workflow

This is for people who work with email data but do not know SQL well.
If you ask questions like “Which emails mention the project?” but don’t want to write SQL, this helps.

It’s good for data analysts, managers, or anyone needing fast email info from databases.


Tools and services used

  • n8n: Visual automation editor to run the workflow.
  • PostgreSQL: Stores structured email metadata.
  • Ollama AI: AI chat model “phi4-mini:latest” to convert questions to SQL.
  • Local file system: Saves and loads database schema as JSON.

Inputs, Process, and Outputs

Inputs

  • User types a natural language question about email data.
  • PostgreSQL database schema is loaded from local JSON or queried live.

Processing Steps

  • Workflow reads database tables and columns.
  • Saves schema info in JSON file locally for faster use.
  • On question input, it merges schema and question.
  • AI node generates a SQL SELECT query matching the schema.
  • Workflow extracts and validates the query syntax.
  • If query is valid, it runs SQL on PostgreSQL.
  • Results are formatted into readable text.
  • The final answer combines SQL query results with AI explanations.

Outputs


Beginner step-by-step: How to use this workflow in n8n

Importing and setup

  1. Download the workflow file using the Download button on this page.
  2. Open the n8n editor where you want to use the workflow.
  3. Click “Import from File” and select the downloaded workflow.
  4. Add your PostgreSQL credentials in the PostgreSQL node.
  5. Enter your Ollama API Key in the Ollama Chat Model node and select model “phi4-mini:latest.
  6. If needed, update any table names, emails, or folder IDs used in the workflow to match your database.

Testing the workflow

  1. Run the workflow manually to check if it loads the database schema and saves the JSON file.
  2. Send a sample question via the Chat Trigger node input to see if it generates a SQL query.
  3. Check that the SQL query runs and returns results.

Activating for production

  1. Turn on the workflow by toggling it live in n8n.
  2. Make sure the webhook URL from the Chat Trigger node is reachable by your chat or API clients.
  3. If using self-host n8n, ensure network and permissions are set correctly.

Customization ideas

  • Change schema queries to point at different database schemas or tables.
  • Edit the AI Agent prompt to add more columns or change question handling.
  • Change the result format node to output CSV or JSON instead of pipe-delimited text.
  • Add caching by improving local JSON saving to avoid DB load every run.
  • Modify the Chat Trigger webhook to connect with Slack or Teams.

Common problems and fixes

No SQL query generated

Sometimes the AI can’t make a query if the question is unclear or too broad.
Try asking more specific questions.

PostgreSQL connection errors

Usually wrong credentials or no access to the database.
Check your PostgreSQL credentials in n8n and test connections outside.

Missing schema JSON file

The file not saved or wrong path.
Re-run the manual schema loading steps. Check file permissions.


Summary of results

→ Quickly get correct SQL queries from plain English questions.
→ Run these queries automatically on PostgreSQL email metadata.
→ Save time and avoid manual SQL errors.
→ See formatted email data results combined with AI chat answers.
Use inside n8n with simple setup and testing.


Automate SQL queries with n8n and Postgres

Visit through Desktop to Interact with the Workflow.

Frequently Asked Questions

The workflow is made for PostgreSQL. Using other databases would need changes to SQL queries and the AI prompt.
Yes, Ollama charges based on your account plan for AI model usage.
All email data stays in your PostgreSQL database and n8n instance. The AI only processes schema and questions, not raw data.
For high volume, scale PostgreSQL and adjust n8n concurrency settings to manage load.

Promoted by BULDRR AI

Related Workflows

Automate Twist Channel Creation and Messaging with n8n

This workflow automates creating and updating a channel in Twist and sending a personalized message to specific users. It eliminates manual setup errors and saves time managing Twist communications.

Automate Ideogram Image Generation with Google Sheets & Gmail

This workflow automates graphic design image generation via Ideogram AI, storing image data in Google Sheets and Google Drive, with email alerts via Gmail. It saves designers hours by automating image creation, remixing, review, and record-keeping.

Automate IT Support with Slack and OpenAI in n8n

Streamline IT support by automating Slack message handling using n8n and OpenAI. This workflow handles Slack DMs, filters bots, queries a Confluence knowledge base, and delivers AI-generated responses, improving support efficiency and response time.

Automate Crypto Analysis with CoinMarketCap & n8n AI Agent

Discover how this unique n8n workflow leverages CoinMarketCap’s multi-agent AI to deliver precise, real-time cryptocurrency insights directly via Telegram. Manage crypto data analysis efficiently with automated multi-source API integration.

Automate Gumroad to Beehiiv Subscriber Sync with n8n

Learn how to automatically add new Gumroad sales customers as Beehiiv newsletter subscribers using n8n automation. This workflow saves time by syncing sales data to Google Sheets CRM and notifying your Telegram channel instantly.

Generate On-Brand Blog Articles Using n8n and OpenAI

This workflow automates the creation of on-brand blog articles by analyzing existing company content using n8n and OpenAI. It extracts article structures and brand voice to produce consistent draft articles, saving significant content creation time.
1:1 Free Strategy Session
Your competitors are already automating. Are you still paying for it manually?

Do you want to adopt AI Automation?

Every hour your team does repetitive work, you're burning real money.
While you wait, faster businesses are cutting costs and moving quicker.
AI and automations aren't the future anymore — they're the present.

Book a live 1-on-1 session where we show you exactly which of your daily tasks can be automated — and what it’s costing you not to.