AI Agent query PostgreSQL database

Hi everyone,

I’m trying to build an AI Agent in n8n that can autonomously query a PostgreSQL database with multiple joined tables.

My goal is to enable the AI Agent to:

  • Understand which tables are available
  • Know the structure of these tables (columns and data types)
  • Generate and execute valid SQL queries

My idea was to create the following 3 Tool Nodes:

  1. Execute SQL Query
  2. Get DB Schema and Tables List
  3. Get Table Definition

I have a few questions:

  • How should each of these nodes be configured so that the Agent can use them properly?
  • How do I provide the schema and table definitions as context for the Agent?
  • Is there a working example or best practice for using Tool Nodes with Agents in n8n when querying relational databases?

Is this even the correct approach in n8n? Or is there a better way to enable an AI Agent to work with a PostgreSQL database?

Any help or insights would be greatly appreciated – especially if someone has already solved this pattern.

Thanks in advance!

Edit: Here is my current workflow. It seems to work more or less, but there is probably a better approach.