How can I generate a database query from a natural language?

Hi everyone,

I’m running n8n locally and working on a workflow with this goal:

  1. A user sends a message via chat

  2. I want the system to automatically generate an SQL query based on the user’s message and run it on my Supabase database — without manually writing or mapping queries myself

Any suggestions on how to approach this?

Use AI to convert natural language to SQL

Use the OpenAI GPT-4 API or a similar LLM (large language model) to convert the user’s message into an SQL query.

Example:
User: “Show me the sales from the last 7 days”
GPT response: SELECT * FROM sales WHERE date > CURRENT_DATE - INTERVAL '7 days';

Yeah, so ideally you’ve got two ways to go about it:

Don’t use RAG with predefined potential queries, just keep the system open. The catch is, users could prompt it to do anything, which brings security risks.

Use predefined queries with examples, feed those to the LLM so it understands what kinds of queries to make. You can also set rules to narrow things down, like only letting it access data related to the user making the request. Then just instruct the system to stick to the example queries and stay within those limits.