AI SQL query generator: write, explain and check SQL safely with AI

AI SQL query generator: write, explain and check SQL safely with AI

An AI SQL query generator turns a question in plain language into a SQL query, and it works well only when it knows your schema, your SQL dialect and what your business terms mean. This guide shows how to give it that context, prompt it, verify the results and keep production data safe.

In shortTL;DR
  • Schema context decides quality: give the AI the table definitions, relationships, a few sample rows and what terms like revenue or active user mean.
  • Name your database and version in the prompt, because date functions and syntax differ between Postgres, MySQL, BigQuery and others.
  • Run AI-generated SQL with a read-only role, a statement timeout and ideally against a replica, never with write access to production.
  • Check every result: row counts, join fan-out, NULL handling, time zones and a comparison with a number you already trust.
  • AI is also good at explaining unfamiliar SQL and reading EXPLAIN plans to suggest indexes.

What is an AI SQL query generator?

An AI SQL query generator is a tool that writes SQL from a plain-language question, such as "monthly revenue by plan for the last six months". It can be a general chat assistant, a feature inside your database console, or a coding agent connected to your database.

All of them use a large language model that has seen a great deal of SQL. What separates a good result from a confident wrong one is context: the model has never seen your database, so it only knows your tables if you show them. With the schema, your dialect and your definitions in front of it, AI writes most everyday queries correctly and saves real time on the complicated ones.

Beyond writing queries, AI is useful for:

  • explaining a query someone else wrote,
  • converting SQL between dialects (MySQL to Postgres, SQL Server to BigQuery),
  • reading EXPLAIN output and suggesting indexes,
  • finding the bug in a query that returns wrong totals,
  • writing migrations, views and test data.

Which AI SQL tools can you use?

You can generate SQL with four kinds of tools, and the right one depends on where your data lives and how much access you want to give the AI.

Tool typeExamplesSees your schema?Runs queries?Best for
Chat assistantChatGPT, Claude, GeminiOnly what you pasteNoOne-off queries, learning, explanations
Built into your database consoleGemini in BigQuery, AI assistants in database IDEs such as DataGripYes, from the connected databaseYou run themAnalysts working in one warehouse
Coding agent with database accessClaude Code or Codex with a database MCP serverYes, it can inspect tablesYes, within the permissions you grantMulti-step analysis, building reports and pipelines
Text-to-SQL inside BI or appsSemantic-layer tools, embedded "ask your data" featuresThrough a curated modelYesNon-technical users asking repeat questions

Gemini in BigQuery, for example, can generate SQL from a natural language prompt or from a comment in the editor, explain a highlighted query, and suggest fixes for query errors (BigQuery docs).

Coding agents are the most capable option and need the most care. Connected through an MCP server, an agent can list tables, run a query, look at the result and refine it. Our list of the best MCP servers covers database servers and their read-only modes.

Why does schema context matter so much?

Schema context matters because the model guesses anything you don't show it: table names, column names, how tables join and what words like "active" mean. Those guesses produce queries that run without errors and return wrong numbers, the worst kind of failure.

Compare two prompts for the same question.

weak prompt
Write a SQL query for monthly revenue by plan.

The model has to invent a payments table, guess whether amounts are in cents, assume refunds don't exist and pick a dialect. A better prompt gives it what it needs:

better prompt
Database: PostgreSQL 16.Tables:CREATE TABLE subscriptions (  id bigint PRIMARY KEY,  account_id bigint NOT NULL,  plan text NOT NULL,            -- 'starter' | 'pro' | 'team'  started_at timestamptz NOT NULL,  canceled_at timestamptz);CREATE TABLE invoices (  id bigint PRIMARY KEY,  subscription_id bigint NOT NULL REFERENCES subscriptions(id),  amount_cents integer NOT NULL, -- negative for refunds  status text NOT NULL,          -- 'paid' | 'open' | 'void'  paid_at timestamptz);Definitions:- Revenue = sum of amount_cents for invoices with status 'paid', refunds included.- Months are calendar months in UTC.Question: monthly revenue in dollars by plan for the last 6 full months.Return month, plan, revenue. Explain any assumption you make.

A typical answer:

generated query
SELECT  date_trunc('month', i.paid_at, 'UTC') AS month,  s.plan,  SUM(i.amount_cents) / 100.0 AS revenueFROM invoices iJOIN subscriptions s ON s.id = i.subscription_idWHERE i.status = 'paid'  AND i.paid_at >= date_trunc('month', now(), 'UTC') - interval '6 months'  AND i.paid_at <  date_trunc('month', now(), 'UTC')GROUP BY 1, 2ORDER BY 1, 2;

What to include in schema context:

  • CREATE TABLE statements (or a schema dump) for the tables involved, with foreign keys.
  • Comments on columns whose meaning or units aren't obvious.
  • Three to five sample rows when values are coded (status, type).
  • Business definitions: revenue, active user, churn, the fiscal calendar.
  • The database engine and version.
Warning

Sample rows can contain personal data. Use made-up or masked rows when you paste into a chat assistant, and check your company's AI policy before sharing real data.

How do you generate SQL with AI step by step?

Treat the AI like a fast analyst who is new to your company: give it the context, ask for its assumptions, and verify before you trust the answer. This procedure works with any tool.

  1. State the question precisely. Include the time window, grain (per day, per account) and filters. "Active accounts" is vague; "accounts with at least one login in the last 30 days" is not.
  2. Provide the schema for the relevant tables, plus definitions and the dialect.
  3. Ask for assumptions. "List any assumption you made" surfaces guesses about refunds, time zones or duplicates.
  4. Read the query before running it. Check joins, filters and grouping against the question.
  5. Run it on a safe connection (read-only, with a timeout) and look at the first rows.
  6. Sanity-check the result against a number you already know, such as last month's revenue from your billing dashboard.
  7. Save it with a comment explaining what it answers, so the next person (or AI) can reuse it.

A reusable prompt template:

prompt template
You are writing {database and version} SQL.Schema (only the relevant tables):{CREATE TABLE statements with comments}Definitions:{business terms and how they map to columns}Question: {precise question with time window and grain}Rules:- Use only the tables and columns above. If something is missing, say so instead of guessing.- Use explicit JOINs and qualify every column with a table alias.- List your assumptions after the query.

The line "if something is missing, say so instead of guessing" does real work. It gives the model permission to stop rather than invent a column, the SQL version of AI hallucinations.

How can AI explain and optimize SQL?

AI is good at turning a dense query into plain language and at reading query plans. Both save time when you inherit SQL or a query gets slow.

To understand a query, paste it with the schema and ask for a line-by-line explanation, the grain of the result, and any edge cases where it might return surprising rows (for example, accounts with no invoices disappearing because of an inner join).

To speed one up, give the AI the query, the schema with existing indexes and the plan:

prompt
This PostgreSQL 16 query takes 9 seconds. Here are the query, the tabledefinitions with their indexes, and the output of EXPLAIN (ANALYZE, BUFFERS).Explain where the time goes, then suggest at most two changes (an index or arewrite), with the expected effect and any write-performance cost.

Always test suggested indexes on a copy or a staging database first. An index that speeds up one query also slows down writes and uses disk, and the AI can't see your full workload.

Converting SQL between dialects

Translating queries between databases is another task AI handles well, as long as you name both sides. Date and time functions, string concatenation, LIMIT versus TOP, boolean types and NULL sorting all differ between engines, and these are exactly the spots where a silent mistake changes results.

prompt
Convert this SQL Server 2019 query to PostgreSQL 16. Keep the output columnsand their names identical. List every function or behavior you changed(dates, string handling, NULL ordering, integer division) and why.

Run the original and the converted query on the same data and compare row counts and totals before you switch over. For a migration with hundreds of queries, have a coding agent convert them in batches and write a script that runs both versions and diffs the results.

How do you keep production data safe when using AI for SQL?

Give AI tools the least access that still answers the question: a read-only role, a timeout, limited tables, and preferably a replica instead of the primary database. This matters most for agents that run queries themselves.

In PostgreSQL, create a dedicated role for AI access:

psql
CREATE ROLE ai_readonly LOGIN PASSWORD 'use-a-long-random-password';GRANT CONNECT ON DATABASE app TO ai_readonly;GRANT USAGE ON SCHEMA analytics TO ai_readonly;GRANT SELECT ON ALL TABLES IN SCHEMA analytics TO ai_readonly;ALTER ROLE ai_readonly SET default_transaction_read_only = on;ALTER ROLE ai_readonly SET statement_timeout = '30s';ALTER ROLE ai_readonly SET idle_in_transaction_session_timeout = '60s';

default_transaction_read_only makes new transactions read-only, and statement_timeout aborts any statement that runs longer than the limit; both default to off (PostgreSQL docs). The SELECT grants are the real protection, since a session can switch read-only mode off again; the settings stop accidents and runaway queries.

More layers worth adding:

  • Use a read replica or a nightly copy so a heavy AI query can't slow down your app.
  • Expose views, not raw tables. An analytics schema with views that leave out emails, addresses and payment details limits what can leak.
  • Use read-only modes in MCP servers. Supabase's MCP server, for example, accepts read_only=true to run queries as a read-only Postgres user and project_ref to limit it to one project (Supabase MCP docs).
  • Keep credentials out of prompts and repos. Reference them through environment variables in your MCP config (Claude Code MCP docs).
  • Review any write query by hand. Migrations and data fixes generated by AI should go through the same review and backup routine as human ones.

How do you check AI-generated SQL?

Check the logic before you run it and the numbers after. Most wrong results come from a handful of patterns.

ProblemHow it shows upCheck
Join fan-outTotals too highCompare COUNT(*) before and after each join; aggregate before joining
Inner join drops rowsMissing accounts or zero-value groupsAsk whether rows without matches should appear; use LEFT JOIN if so
NULL handlingAverages and counts slightly offLook at COUNT(column) vs COUNT(*); check WHERE x <> 'a' excluding NULLs
Time zones and boundariesOff-by-one-day or partial monthsConfirm the time zone and whether ranges are inclusive
Wrong definitionPlausible but different numberCompare with a figure from the source system
Invented columnsQuery errors, or a similar column used by mistakeMake sure every column exists in the schema you gave

A practical habit: before trusting a new query, reproduce one number you already know (last month's revenue, yesterday's sign-ups). If it matches, the joins and filters are probably right. Our guide to AI for data analysis covers more sanity checks for charts and summaries.

How to start using AI for SQL today

Set up a safe, repeatable workflow once and every later query gets faster.

  1. Create a read-only role with a statement timeout, pointed at a replica or an analytics schema.
  2. Write a short schema-and-definitions file for your most-used tables: CREATE TABLE statements, column notes and business terms.
  3. Save the prompt template above and reuse it for every question.
  4. Pick one recurring report you build by hand and have AI draft the query; verify it against last month's known numbers.
  5. Keep verified queries in a shared folder with comments, so they become examples for future prompts.
  6. If you want an agent to refresh reports on a schedule, give it only the read-only role. Running it on an isolated, always-on server such as an Orkio box keeps those credentials off your laptop.

Frequently asked questions

Can ChatGPT or Claude write SQL queries?

Yes. General chat assistants write correct SQL for most everyday questions when you paste the relevant table definitions and say which database you use. Without schema context they guess table and column names, which is the most common source of wrong queries.

Is it safe to connect an AI tool to my production database?

Only with strict limits. Use a dedicated read-only database role, a statement timeout, ideally a read replica, and no access to tables with sensitive personal data unless you need them. Never give an AI agent credentials that can modify or delete production data.

How accurate are AI SQL generators?

Accuracy depends far more on context than on the tool. Simple single-table queries are usually right; queries with several joins, ambiguous business terms or unusual schemas often run without errors but return the wrong numbers. Treat every result as a draft until you have checked it against a known figure.

Can AI convert SQL between databases?

Yes, translating between dialects such as MySQL, Postgres, SQL Server and BigQuery is one of the tasks AI does well. Tell it the source and target database and version, and test the converted query on real data, because date handling, string functions and NULL behavior differ.

What is text-to-SQL?

Text-to-SQL is the general term for systems that convert a natural language question into a SQL query. It ranges from asking a chat assistant to built-in features in tools like BigQuery to agents that inspect a database schema and run queries themselves.

SOURCES

  1. PostgreSQL 18 docs: Client connection defaults
  2. Google Cloud docs: Write queries with Gemini assistance in BigQuery
  3. Supabase docs: Model Context Protocol
  4. Claude Code docs: MCP
  • #sql
  • #ai for data
  • #databases
  • #text to sql
  • #postgres
Orkio team

The team building Orkio. We write about putting AI to work: coding agents that run overnight, always-on boxes and pull requests ready by morning.

Keep reading

All posts

07:06 · YOU MERGED #128

Go to sleep. Wake up to pull requests.

Start for $19 a month
© 2026 Orkio · Hosted in Europe TürkçeStatus