Skip to main content

n8n Database Automation: Postgres and MySQL Workflows

Automate SQL with n8n: connect Postgres or MySQL safely, schedule reports, react to new rows, use query parameters, and fix the common connection errors.

Founder of IImagined.ai

Published
Jan 15, 2025
Updated
Oct 14, 2026
Reading time
11 min read
Quick answer

To automate a database with n8n, create a credential for Postgres, MySQL, Microsoft SQL, Oracle Database or MongoDB, then pair the database node with a trigger: a Schedule Trigger for reports and cleanup, the Postgres Trigger for new or changed rows, or a Webhook for events from your app. Pass values into SQL through the node's Query Parameters option, which n8n sanitizes against SQL injection, and connect with a database user that has only the permissions each workflow needs.

n8n database automation means pairing a database node with a trigger: a schedule for reports and cleanup, a row-change trigger for events, or a webhook from your app. The two habits that keep it safe are a database user with only the rights each workflow needs, and values passed through Query Parameters instead of pasted into SQL.

Checked against n8n's Postgres, Postgres Trigger, MySQL, Microsoft SQL, Oracle Database and MongoDB node docs, its Data tables page and the 3.0 breaking changes, on 1 and 14 October 2026. An earlier version of this page quoted time savings and execution times that had no source; they are gone.

Quick answer: a first database workflow
  1. 1
    Create a database user for n8n

    Read-only with a statement timeout for reports.

  2. 2
    Add the credential

    Host, database, user, password, port, SSL set to Require.

  3. 3
    Test with SELECT 1

    Execute Query, before building anything else.

  4. 4
    Pick a trigger

    Schedule, Postgres Trigger or Webhook.

  5. 5
    Use Query Parameters

    Placeholders like $1 in SQL, values in the option.

  6. 6
    Add an error workflow and publish

    So a failed run alerts someone.

What can n8n do with a database?

Most of what a small team does by hand in a SQL client, as long as the result goes somewhere else. The jobs people automate most often:

  • Scheduled reports: run a query every morning or week and send the result by email or Slack.
  • Syncing: copy new or changed rows into a CRM, a spreadsheet or another database.
  • Event reactions: start a workflow when a row is inserted, updated or deleted.
  • Maintenance: archive or delete expired data in small, logged batches.
  • Enrichment: read a record, call an API, and write the result back.
  • AI lookups: let an AI agent read specific tables to answer questions.

Databases with built-in n8n nodes

Databasen8n nodeOperations
PostgreSQLPostgres and Postgres TriggerSelect, Insert, Insert or Update, Update, Delete, Execute Query; trigger on insert, update or delete
MySQLMySQLSelect, Insert, Insert or Update, Update, Delete, Execute SQL
Microsoft SQL ServerMicrosoft SQLExecute a query; insert, update and delete rows
Oracle Database 19c or laterOracle DatabaseSelect, Insert, Insert or Update, Update, Delete, Execute SQL
MongoDBMongoDBAggregate, find, insert, update, find and update, find and replace, delete; manage search indexes
Warehouses and other storesSnowflake, BigQuery, Databricks, Supabase, TimescaleDB, QuestDB, CrateDB, Redis, Elasticsearch, Cosmos DB, FirestoreVaries by node

Each of the five main app nodes can also be connected to an AI agent as a tool. For small amounts of data you do not want in your production database, n8n's built-in Data tables need no external database. All data tables in an instance share a 200 MiB limit by default, which self-hosted users can change with N8N_DATA_TABLES_MAX_SIZE_BYTES. For the other engines, see our guides to n8n and MongoDB and n8n and SQL Server.

Step 1: create a database user for n8n

Give n8n its own login with only the rights each workflow needs. For a reporting workflow on PostgreSQL, that means read-only access and a query timeout:

-- Read-only login for reporting workflows
CREATE ROLE n8n_reporting LOGIN PASSWORD 'use-a-long-random-password';
GRANT CONNECT ON DATABASE app_db TO n8n_reporting;
GRANT USAGE ON SCHEMA public TO n8n_reporting;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO n8n_reporting;

-- Also cover tables created later by the role running this command
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO n8n_reporting;

-- Stop runaway queries
ALTER ROLE n8n_reporting SET statement_timeout = '30s';

ALL TABLES IN SCHEMA covers the tables that exist today, and the default-privileges line covers new ones; see PostgreSQL's GRANT and ALTER DEFAULT PRIVILEGES references. For workflows that write, create a second user with INSERT or UPDATE on only the tables that workflow touches. Keep every password in the n8n credential, never in a query or a Code node.

Step 2: add the credential in n8n

  1. Add a Postgres node to a workflow and create a new credential from its Credential to connect with field.
  2. Enter Host, Database, User, Password and Port. PostgreSQL listens on 5432 unless your provider says otherwise; MySQL uses 3306.
  3. Set SSL. n8n offers Allow, Disable and Require; use Require for any database reached over the internet and leave Ignore SSL Issues off.
  4. If the database is only reachable over SSH, turn on SSH Tunnel. n8n's credential docs say this works when an SSH server runs on the same machine as Postgres, and that the AI Agent node cannot use SSH tunnels.
  5. Save, then run SELECT 1 with Execute Query to confirm the connection.

Network access

  • n8n Cloud: outbound requests come from the addresses on n8n's IP address list, and n8n recommends allowlisting all of them. The same page warns that "an IP allowlist alone doesn't prove a request came from your instance", because the addresses are shared, so keep SSL and a strong password as well.
  • Self-hosted in Docker: inside a container, localhost means the container, not your machine. Use host.docker.internal as the host (on Linux, start n8n with --add-host host.docker.internal:host-gateway), or put both containers on one Docker network and use the database container's name. n8n's MySQL troubleshooting page walks through each setup.

Still choosing where the database lives? Our Postgres hosting comparison covers the managed options.

Workflow 1: a scheduled SQL report by email

Four nodes: Schedule Trigger, Postgres (Execute Query), HTML (Convert to HTML Table) and Gmail (Send).

  1. Schedule Trigger: Trigger Interval Weeks, Monday, 8am. The node uses the workflow's timezone if you set one, otherwise the instance timezone (America/New_York by default on self-hosted n8n). Publish the workflow, or the schedule never runs.
  2. Postgres, Execute Query: run the query below.
  3. HTML, Convert to HTML Table: this operation turns every row into one item with a table field.
  4. Gmail, Send: set Email Type to HTML and Message to {{ $json.table }}. The Gmail node appends an n8n attribution line by default; turn off Append n8n attribution in its options if you do not want it.
-- Last week's signups per day (example schema: users.created_at, users.plan)
SELECT
  to_char(created_at::date, 'YYYY-MM-DD') AS day,
  count(*) AS signups,
  count(*) FILTER (WHERE plan <> 'free') AS paid_signups
FROM users
WHERE created_at >= date_trunc('week', now()) - interval '7 days'
  AND created_at <  date_trunc('week', now())
GROUP BY 1
ORDER BY 1;

The to_char call is deliberate. n8n's Postgres troubleshooting page explains that the driver turns DATE values into full ISO datetimes, which can land on the wrong day in your timezone. Formatting the date in SQL keeps it as YYYY-MM-DD. For other schedules, the n8n cron expression guide has the expressions.

Workflow 2: run a workflow when a row changes

Use the Postgres Trigger node. Choose Listen and Create Trigger Rule, pick the table and event, and n8n creates a trigger and procedure when you publish the workflow, then removes them when you unpublish it. It can also Listen to Channel for notifications you send yourself.

Row changes, with a catch-up for missed events
  1. 01
    Postgres Trigger

    Insert on orders. The row arrives under payload.

  2. 02
    Fetch the full record

    A parameterized query on the payload ID.

  3. 03
    Send it on

    CRM, Slack or an invoicing API.

  4. 04
    Mark it handled

    Update synced_at on the row.

  5. 05
    Scheduled catch-up

    A second workflow picks up rows where synced_at is still null.

An order's ID is {{ $json.payload.id }} (check the trigger's output panel for your field names). Fetch the full record with a parameterized query:

SELECT o.id, o.total_amount, c.email
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.id = $1;

-- Options > Query Parameters:
{{ [ $json.payload.id ] }}

Source for the payload limit: PostgreSQL's NOTIFY reference. n8n has no equivalent trigger node for MySQL, SQL Server, Oracle or MongoDB. Poll instead: run a Schedule Trigger every few minutes, select rows whose updated_at is later than the last run, and keep that timestamp in a Data table.

Which trigger to use
Only the database knows
A Webhook from the app is simplest and carries exactly the fields you choose.
A Webhook from the app. It works the same for any database.
Your app can call n8n
Postgres Trigger, plus a scheduled catch-up for anything missed.
Schedule Trigger polling updated_at, with the last run time kept in a Data table.
Postgres
MySQL, SQL Server, Oracle, MongoDB

Workflow 3: clean up old rows in small batches

-- Delete up to 5,000 expired sessions per run and report the count
WITH deleted AS (
  DELETE FROM user_sessions
  WHERE id IN (
    SELECT id FROM user_sessions
    WHERE last_activity < now() - interval '30 days'
    LIMIT 5000
  )
  RETURNING id
)
SELECT count(*) AS deleted_rows FROM deleted;

Schedule it hourly and post {{ $json.deleted_rows }} to Slack. Small batches keep locks short and make each run easy to audit. Before scheduling any delete, run the inner SELECT on its own to see what would go, and give the workflow a user that can delete from this one table only.

For riskier jobs, put a person in the loop: the Slack node's Send and Wait for Response operation pauses the workflow until someone approves. When several writes must succeed together, set Query Batching to Transaction:

Query BatchingWhat it doesUse it for
Single QueryOne query for all incoming itemsBulk reads and inserts where one failure can fail the lot
IndependentlyOne query per incoming itemItems that should succeed or fail on their own
TransactionAll queries in one transaction; Postgres rolls back everything if one failsWrites that must succeed together

How do you write SQL that cannot be injected?

Use placeholders and the Query Parameters option. n8n's Postgres and MySQL docs state that "n8n sanitizes data in query parameters, which prevents SQL injection." The most common mistake in n8n database workflows is the opposite: dropping an expression straight into SQL.

The same lookup, two ways
Unsafe
  • WHERE email = '{{ $json.email }}'
  • A quote in the input can change the query
  • The database user can do whatever the injected SQL asks
Safe
  • WHERE email = $1
  • Query Parameters: {{ [ $json.email ] }}
  • n8n sanitizes the value before it reaches the database
-- Safe
SELECT id, email, plan FROM customers WHERE email = $1;

-- Options > Query Parameters:
{{ [ $json.email ] }}
  • Use $1:name for identifiers such as a table name, as in n8n's own example SELECT * FROM $1:name WHERE email = $2.
  • For IN lists, generate one placeholder per value and pass the array as the parameters. The Postgres troubleshooting page shows this pattern:
SELECT color, shirt_size FROM shirts
WHERE shirt_size IN ({{ $json.sizes.map((v, i) => '$' + (i + 1)).join(', ') }});

-- Options > Query Parameters:
{{ $json.sizes }}

Where they fit, prefer the Select, Insert, Update and Insert or Update operations: they build the SQL for you from mapped columns.

Can an AI agent read your database?

Yes, through a database node attached to the AI Agent node as a tool. The older SQL Agent mode belongs to version 1 of the AI Agent node, which the 3.0 breaking changes remove, with a Postgres or MySQL tool as the documented replacement. The model can fill in tool parameters itself, or you can mark specific fields with $fromAI():

{{ $fromAI('customer_email', 'Email address of the customer', 'string') }}
  • Give the tool the read-only user from Step 1, with its statement timeout.
  • Prefer the Select operation on a fixed table, with the model filling only the filter value, over letting it write free-form SQL.
  • Set a row limit so one question cannot pull a whole table into the prompt.
  • Keep writes out of agent tools, or put an approval step in front of them.
  • Log each question and the query it produced so you can review mistakes.

The agent setup itself is in our n8n and OpenAI guide.

Performance and reliability

Before a database workflow runs unattended
  • Big tables are paged: n8n suggests 200 rows per execution, not 10,000
  • Query Batching is chosen on purpose, with Transaction for linked writes
  • Output Large-Format Numbers As is Text for values longer than 16 digits
  • Times are stored in UTC and the workflow timezone is set
  • Columns in WHERE and JOIN clauses are indexed
  • An error workflow starting with the Error Trigger is selected in Settings
  • Each workflow uses its own database user with the narrowest grants

n8n's memory guide says it "doesn't restrict the amount of data each node can fetch and process", hence the paging. The MySQL node returns DECIMAL values as strings by default to avoid precision loss. An Error Trigger workflow fires for automatic runs, not manual tests; our n8n error handling guide shows the setup. Check slow queries with PostgreSQL's EXPLAIN.

Troubleshooting common errors

Connection refused or timeout

Check the host and port, the database firewall, and whether n8n runs in Docker (see Network access above). On n8n Cloud, confirm the database allows n8n's outbound IP addresses.

SSL errors

Managed databases usually require SSL, so pick Require. Use Ignore SSL Issues only for a short test, never in production.

The Postgres Trigger never fires

Make sure the workflow is published, the user can create triggers and procedures, and the row fits within the 8,000-byte notification limit.

Dates are a day off or big numbers look wrong

Format dates with to_char in SQL, and switch large-number output to Text.

The query works in my SQL client but returns nothing in n8n

Run it in the client as the same database user n8n uses, check that $1 maps to the first parameter value, and look at the node's input: expressions are evaluated per item.

When is n8n the wrong tool?

When the job never leaves the database. n8n is strongest when database work connects to other apps: a report that lands in Slack, a new order that updates a CRM, an approval before a delete. Refreshing a summary table every night is simpler with a database-side scheduler such as pg_cron, and moving millions of rows between warehouses suits a dedicated ELT tool better than item-by-item workflows.

Next steps

Start with one read-only report, add an error workflow, then move on to syncing and triggers. For the setup around it, see self-hosting n8n, n8n API integration and n8n CRM automation. If you would rather build your own AI product than run client automations, AI SaaS Builder covers database design, authentication and Supabase in depth, along with the Claude API, Next.js and Stripe billing; Supabase RLS explained is a good first read on the database side.

n8n database automation: FAQ

Which databases does n8n support?

n8n has built-in nodes for PostgreSQL, MySQL, Microsoft SQL Server, Oracle Database (19c or later) and MongoDB, plus Snowflake, Google BigQuery, Databricks, Supabase, TimescaleDB, QuestDB, CrateDB, Redis, Elasticsearch, Azure Cosmos DB and Google Cloud Firestore. For light storage inside n8n itself, such as dedupe markers or lookup lists, it also has Data tables.

How do I prevent SQL injection in n8n?

Do not paste expressions such as {{ $json.email }} straight into SQL. Write placeholders like $1 and $2 and pass the values in the Query Parameters option of the Postgres or MySQL node; n8n's docs say it sanitizes query parameters, which prevents SQL injection. Also connect with a database user that has only the permissions the workflow needs.

Can n8n start a workflow when a database row changes?

Yes for PostgreSQL. The Postgres Trigger node can create a trigger for insert, update or delete events on a table, or listen to a channel you notify yourself. The database user needs permission to create triggers and procedures. For MySQL, SQL Server, Oracle and MongoDB, poll on a schedule for rows changed since the last run.

Can n8n Cloud connect to my own database?

Yes, if the database accepts connections from the internet or through an SSH tunnel. Allowlist the n8n Cloud outbound IP addresses listed in n8n's docs. Because those addresses are shared across customers, n8n warns that an allowlist alone does not prove a request came from your instance, so still require SSL and a strong password.

Can an AI agent in n8n query my database?

Yes. Connect a database node such as Postgres to the AI Agent node as a tool, and the model fills in parameters itself or through $fromAI(). The older SQL Agent mode belongs to version 1 of the AI Agent node, which n8n 3.0 removes. Give the tool a read-only user with a statement timeout, and require approval before any write.

How much data can an n8n workflow pull from a database?

n8n does not cap how much data a node fetches, so very large result sets can run out of memory. n8n's memory guide recommends processing smaller chunks, for example 200 rows per execution instead of 10,000, with Loop Over Items and sub-workflows. Page through big tables rather than selecting them whole.

Free · no card needed

Start with the free Starter Kit.

A unit economics calculator from AI SaaS Builder, plus four more working files.

Starter Kit5 files · free
See All Access: $99/mo →30-day money-back guarantee