Chat with Your Database Using AI
· By AI Compare
Ask questions in plain English and get answers from your SQL database, with safety rules built in.
What you will build
A chat interface where anyone on your team can ask questions like "What were our top 10 customers by revenue last quarter?" and get an answer from your database, without writing SQL. An AI agent reads the database schema, writes the SQL query, runs it and explains the result.
This follows n8n's "Chat with PostgreSQL database" template; the same approach works with MySQL, SQLite and other SQL databases.
Workflow structure
| Node | Role |
|---|---|
| Chat Trigger | Where users ask questions |
| AI Agent | Decides which tools to call |
| OpenAI Chat Model (or another model) | Writes SQL and the final answer |
| Simple Memory | Multi-turn context ("now only for Germany") |
| Tool: Get DB schema and tables list | Lists tables so the agent knows what exists |
| Tool: Get table definition | Columns and types for a specific table |
| Tool: Execute SQL query | Runs the query the agent writes |
The Postgres tools are Postgres nodes used as agent tools, each with a clear description of what it does.
Safety first: use a read-only user
Never connect an AI agent to your database with an admin account. Create a dedicated user with read-only access to the tables it needs:
CREATE USER ai_reader WITH PASSWORD 'strong-password';
GRANT CONNECT ON DATABASE shop TO ai_reader;
GRANT USAGE ON SCHEMA public TO ai_reader;
GRANT SELECT ON orders, customers, products TO ai_reader;
Better still, point it at a read replica or a reporting copy, not production.
System message tips
- "Only run SELECT queries. Never modify data."
- "Always check the schema before writing a query."
- "Limit results to 100 rows unless the user asks for more."
- "Explain the answer in plain language and show the key numbers in a table."
- Add business definitions: "Revenue means
orders.totalwherestatus = 'paid'."
Make answers better
- Add comments to tables and columns in the database; the schema tool can return them.
- Create views for common questions (for example
monthly_revenue) so the model writes simpler queries. - Log each question, generated SQL and result for review.
Where it fits
- Ops and sales teams who wait on analysts for simple numbers.
- Founders who want quick answers from their product database.
For complex reporting, dashboards are still better; the chat is for ad-hoc questions.
Related
- RAG chatbot over documents (for unstructured text)
- Run local LLMs with Ollama to keep data fully private


