Make Waves '26 tickets are live. Join us in Prague, Oct 19–20, for two days of AI, automation, and what's next. Save with early-bird pricing!

Jul 2, 2026 | 10 minutes

Agent SQL: how to build an AI agent that queries your database

Build an AI agent that turns natural language into SQL queries against your database using Make, with steps, tests and variations.

Agent sql how to build an AI agent that queries your database

Agent SQL is a workflow where an AI agent translates plain English questions into safe SQL queries, runs them against your database, and returns readable answers.

With more than 98% of Databricks SQL customers now using AI/BI to give every employee direct access to data, business teams need self-serve data access.

This guide shows how Make AI agents turn questions into reliable SQL answers using a single visual scenario.

What you need before building an agent SQL workflow

Before building an agent SQL scenario in Make, gather the access, credentials, and guardrails the workflow depends on.

The list below covers the minimum viable setup for a read-only-first deployment that turns natural language questions into validated SQL against your production or replica database.

  • A Make account on a paid plan that supports enough operations for your query volume and access to the Scenario Builder.

  • Database access through a supported connector such as the MySQL integration, PostgreSQL, or Microsoft SQL Server, ideally pointed at a read replica with a least-privileged user.

  • API credentials for your chosen LLM provider (OpenAI, Anthropic, or Azure OpenAI) with a key scoped to this scenario.

  • A schema dictionary or table catalog stored in a Make data store, documented in the data stores docs, so the agent grounds SQL in real column names.

  • A reviewer channel in Slack or email for query approvals and audit logging.

The problem: why raw database access blocks business users

Raw database access blocks business users because writing correct SQL requires schema knowledge, join logic, and dialect fluency that most marketers, operators, and account managers do not have.

The result is a persistent SQL skill gap: revenue leaders who need a churn cut by segment, or a finance analyst who wants yesterday's refunds by region, file a ticket and wait.

Slow data requests then pile up in the analytics queue, where a five minute question becomes a three day round trip through Jira, Slack threads, and clarification calls.

The downstream cost is decisions made on stale dashboards or gut feel.

Analysts burn hours on repetitive lookups instead of modeling work, and business teams stop asking questions because the wait is not worth it.

Connecting a chat interface directly to production tables is risky too, since unconstrained queries can scan billions of rows or expose sensitive columns.

This is where AI automation explained through a controlled scenario changes the economics, giving business users natural language access while keeping guardrails on the database itself.

The Make scenario that turns questions into SQL answers

The Make scenario that turns questions into SQL answers is an agentic loop where a natural language question enters Make, an AI agent plans the query, a database module runs the SQL, and a formatted answer returns to the requester.

The pattern uses Make's AI agents platform to orchestrate reasoning, tool calls, and validation inside a single visual canvas.

At the entry point, a Slack - Watch Messages or Webhooks - Custom Webhook module captures the user question.

The question flows into AI Agents - Run an Agent, which holds the schema context, allowed tables, and tool definitions.

The agent decides whether to query, clarify, or refuse, then calls a MySQL - Execute a Query (Advanced) or PostgreSQL - Execute a Query (Advanced) module through a structured tool call.

Results return as bundles, which an Aggregator reshapes into a single payload.

The agent then drafts a plain language explanation, and a Slack - Create a Message module delivers the answer back to the original channel.

Guardrails sit on every route: a Filter blocks destructive statements, a Router separates read paths from escalation paths, and a Set Variable module records audit metadata.

The Scenario Builder makes each hop inspectable, so reviewers can trace the question, the generated SQL, and the returned rows in one place.

How to build the agent SQL scenario in Make

Building the agent SQL scenario in Make takes seven configured steps inside the Scenario Builder, starting with an input trigger and ending with a formatted response back to the user.

Each module in the chain has one job: receive the question, classify intent, generate SQL against an allowlisted schema, validate the query, execute it through a read-only connection, summarize results with an LLM, and deliver the answer.

Follow the steps below in order, keeping the scenario in inactive state until step 7 testing passes.

Step 1: Configure the agent trigger

Create a new scenario and add a Webhooks - Custom Webhook trigger as the entry point, since Make's AI Agents app has no dedicated invocation trigger.

The trigger receives the natural language question, the user identifier, and a session token used downstream for logging.

Define an explicit data structure so the bundle output is typed.

  • Accept JSON fields: question, user_id, session_id.

  • Set scheduling to Immediately so the scenario runs on each invocation.

  • Enable store incomplete executions for replay during debugging.

Step 2: Load schema context

Add a Data Store - Get a Record module that retrieves a curated schema document describing only the tables the agent is allowed to query.

This allowlist drives every later step and is the foundation of the SQL injection guard.

Store table names, column names, types, and short business descriptions in one record per database.

Step 3: Generate SQL with an LLM

Connect OpenAI - Generate a Completion (or Anthropic Claude - Create a Prompt) and pass the schema context plus the user question.

Instruct the model to return JSON with two fields: sql and rationale.

Refer to Make's LLM integration guide for prompt patterns that produce parseable structured output.

  • Set temperature to 0 for deterministic SQL.

  • Force JSON mode so downstream parsing is reliable.

  • Inject the allowlisted tables verbatim into the system prompt.

Step 4: Validate the SQL before execution

Insert a Router followed by a Tools - Set Variable module that parses the generated SQL and runs three checks: statement type must be SELECT, every table referenced must appear in the allowlist, and no banned keywords (DROP, DELETE, UPDATE, INSERT, ALTER, TRUNCATE, GRANT) may appear.

Failed validation routes to a Slack - Create a Message alert channel and returns a polite refusal to the user.

PRO TIP: Always execute the generated SQL through a parameterized MySQL - Execute a Query (Advanced) or PostgreSQL - Execute a Query (Advanced) call with the connection authenticated as a read-only database user. Combine that with the allowlist check in step 4, and SQL injection from agent-generated queries becomes a closed surface: the credential cannot mutate data even if validation is bypassed.

Step 5: Execute against a read-only connection

Add the database module matching your stack: MySQL - Execute a Query (Advanced), PostgreSQL - Execute a Query (Advanced), Microsoft SQL Server - Execute a Query (Advanced), or BigQuery - Make an API Call.

Configure the connection with a dedicated read-only DB user whose grants permit only SELECT on the allowlisted tables.

Set a statement timeout of 30 seconds at the database level so runaway queries cannot hold operations open.

Step 6: Summarize results for the user

Pipe the result set into an Iterator if you need row-level handling, then an Aggregator to collapse the data into a single text blob.

Pass that blob to a second OpenAI - Generate a Completion call that turns rows into a plain English answer with the original question as context.

Patterns from how to build AI agents apply directly here.

Step 7: Return the answer and log

Send the summary back through Webhooks - Webhook Response or Slack - Create a Message, and write the full transaction (question, SQL, row count, latency) to Google Sheets - Add a Row for audit.

Move long-running result formatting into a child scenario using the subscenarios feature to keep the main flow responsive.

PRO TIP: Wrap step 5 in an error handler with a Break module set to three retries on transient connection failures, but route deterministic SQL errors (syntax, permission denied) to a Tools - Set Variable that feeds the error message back to step 3 for a single repair attempt. This module-by-module config recovers gracefully without infinite loops.

How to test and troubleshoot the SQL agent

Test the SQL agent by running a controlled set of natural language questions against a staging database before promoting the scenario to production.

Start with read only queries that have known answers, then expand to ambiguous prompts that stress the agent's schema understanding.

Use Make's built in run history to inspect each bundle, confirm the generated SQL matches intent, and verify that the Router sends destructive statements to a rejection path.

Pair this with agent transparency practices so reviewers can trace every decision.

Common SQL errors and schema mismatch fix patterns to watch for:

  • Schema mismatch: agent references a column that no longer exists. Fix by refreshing the schema context passed into OpenAI - Generate a Completion on every run.

  • Syntax errors: missing quotes or dialect drift between Postgres and MySQL. Add a validation module that parses SQL before execution.

  • Timeouts: long scans on unindexed tables. Cap query rows and set a statement timeout in the connection.

  • Permission denied: service account lacks SELECT on a view. Audit grants in the database role.

Outcomes you can expect from an agent SQL deployment

An agent SQL deployment in Make shifts database access from a queue of ticket requests to a self-serve conversation, producing faster query time for business users and fewer analyst tickets for the data team.

Once the scenario is live, marketing leads, finance partners and operations managers can ask plain English questions inside Slack or a web form, and the OpenAI - Generate a Completion module paired with a guarded MySQL - Execute a Query (Advanced) module returns the rows within seconds.

Teams typically see analyst backlogs shrink as repetitive lookups, weekly revenue snapshots and cohort counts move out of the queue.

The Celonis agent story shows how similar AI scenarios reduce manual review effort, while the Perk efficiency story illustrates how internal automation frees specialists to focus on higher value modeling work instead of report assembly.

Variations and next steps for your SQL agent

The core scenario adapts to many team contexts once the validation and execution pattern is in place.

Swap the chat trigger for a webhook, route results into a BI tool, or layer in role based filters so the same agent serves finance, support, and product analytics teams.

For reference architectures across connected systems, the API connectivity guide shows how to extend reach beyond native connectors.

Use case

Approach

Difficulty

Finance close queries

Add a Router for read only views plus Slack - Create a Message approvals

Medium

Support ticket analytics

Trigger from Zendesk, return charts via Google Sheets - Add a Row

Low

Product usage exploration

Embed OpenAI - Generate a Completion with cached schema context

Medium

Cross database joins

Use HTTP - Make a Request against a federation layer

High

Conclusion

An agent SQL workflow in Make turns plain language questions into governed database answers, giving analysts and operators direct value without exposing raw credentials or risky write access.

The recap is concrete: a scenario receives a question, an LLM module drafts read only SQL against a schema you publish, a guardrail Router validates the statement, a database module executes it, and a final module returns a readable summary with the underlying rows.

That pattern scales from a single team dashboard to company wide self serve reporting.

Map your schema, pick one high traffic question pattern, and get started for free to ship your first agent SQL scenario this week.

Frequently asked questions

Q1: What is an agent SQL system?

An agent SQL system is an AI workflow that converts plain language questions into validated SQL queries, executes them against a database, and returns formatted answers. In Make, this runs as a scenario combining an LLM module with database modules and safety guardrails.

Q2: Is it safe to let an AI agent run SQL queries?

It is safe when you enforce safety guardrails. Use a read-only database user, restrict the agent to approved views, validate generated SQL with a Router that blocks DELETE, DROP, UPDATE and TRUNCATE statements, and log every query for audit before the scenario executes it.

Q3: Which databases work with Make for agent SQL?

Supported databases include PostgreSQL, MySQL, Microsoft SQL Server, and Oracle through native Make module connectors. BigQuery, Snowflake, and Airtable also work through their dedicated apps. For other engines like DuckDB or ClickHouse, use the HTTP - Make a Request module against their REST API.

Q4: Do I need to fine-tune a model for text-to-SQL?

No fine-tuning is required for most cases. Frontier models from OpenAI and Anthropic handle text-to-SQL well when you pass the schema, column descriptions, and two or three example queries in the system prompt of the OpenAI - Generate a Completion module.

Q5: How does Make handle long-running queries?

Make handles long-running queries through scenario timeout settings and asynchronous patterns. Configure the database module with a query timeout, then use a Router to send heavy queries to a queue table the agent polls later, keeping the main scenario responsive for interactive users.


Schema (JSON-LD) — updated wordCount and dateModified only:

<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"BlogPosting","headline":"Agent SQL: how to build an AI agent that queries your database","description":"Build an AI agent that turns natural language into SQL queries against your database using Make, with steps, tests and variations.","keywords":"agent sql","wordCount":2292,"author":{"@type":"Person","name":"Raife Dowley"},"publisher":{"@type":"Organization","name":"Make","logo":{"@type":"ImageObject","url":"https://images.ctfassets.net/un655fb9wln6/5drzJqeJykwoS5uqQRr4in/6a1e399130f279aee935213d5df437a5/Copy_of_Logo-RGB-Color_2x.png"}},"datePublished":"2026-06-29","dateModified":"2026-07-02","mainEntityOfPage":{"@type":"WebPage","@id":"https://www.make.com/en/blog/agent-sql"}},{"@type":"FAQPage","mainEntity":[{"@type":"Question","name":"What is an agent SQL system?","acceptedAnswer":{"@type":"Answer","text":"An agent SQL system is an AI workflow that converts plain language questions into validated SQL queries, executes them against a database, and returns formatted answers. In Make, this runs as a scenario combining an LLM module with database modules and safety guardrails."}},{"@type":"Question","name":"Is it safe to let an AI agent run SQL queries?","acceptedAnswer":{"@type":"Answer","text":"It is safe when you enforce safety guardrails. Use a read-only database user, restrict the agent to approved views, validate generated SQL with a Router that blocks DELETE, DROP, UPDATE and TRUNCATE statements, and log every query for audit before the scenario executes it."}},{"@type":"Question","name":"Which databases work with Make for agent SQL?","acceptedAnswer":{"@type":"Answer","text":"Supported databases include PostgreSQL, MySQL, Microsoft SQL Server, and Oracle through native Make module connectors. BigQuery, Snowflake, and Airtable also work through their dedicated apps. For other engines like DuckDB or ClickHouse, use the HTTP - Make a Request module against their REST API."}},{"@type":"Question","name":"Do I need to fine-tune a model for text-to-SQL?","acceptedAnswer":{"@type":"Answer","text":"No fine-tuning is required for most cases. Frontier models from OpenAI and Anthropic handle text-to-SQL well when you pass the schema, column descriptions, and two or three example queries in the system prompt of the OpenAI - Create a Chat Completion module."}},{"@type":"Question","name":"How does Make handle long-running queries?","acceptedAnswer":{"@type":"Answer","text":"Make handles long-running queries through scenario timeout settings and asynchronous patterns. Configure the database module with a query timeout, then use a Router to send heavy queries to a queue table the agent polls later, keeping the main scenario responsive for interactive users."}}]},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https://www.make.com/en"},{"@type":"ListItem","position":2,"name":"Blog","item":"https://www.make.com/en/blog"},{"@type":"ListItem","position":3,"name":"Agent SQL: how to build an AI agent that queries your database","item":"https://www.make.com/en/blog/agent-sql"}]}]}</script>

Raife Dowley

Raife Dowley

Raife is a Content Specialist with a background in marketing and campaign management. Transitioning from hands-on platform work to content, he developed a talent for translating technical concepts into clear, engaging narratives that actually resonate with readers.

Like this use case? Spread the word.

Get monthly automation inspiration

Join 350,000+ users to get the freshest content delivered straight to your inbox