AI for Writing SQL Queries: Provide Context and Check Results

An AI assistant can write SQL faster than most developers can type it, but the quality depends on how much context you supply about the schema and the business rules. This guide shows how to give that context and verify the result.

Updated 4 min read

An AI assistant can write SQL queries quickly and accurately when it has the information it needs: table names, column names, relationships, and the business rule behind the query. Without that context, it writes plausible SQL that may not match your schema or your intent.

The key habit is to supply context before asking for a query, then verify the result before running it on real data. Tools like fenbs let you keep the business definitions and the approved query decisions in one place, so every developer and AI working on the same database starts from the same understanding.

What context an AI needs to write good SQL

A good AI-generated query depends on four kinds of context: the schema, the relationships, the business definition, and the output format.

  • Schema: table names, column names, and data types for the relevant tables. Paste the CREATE TABLE statements or a simplified list.
  • Relationships: which columns join which tables, including foreign keys. If the AI has to guess, it will guess wrong.
  • Business definition: what the query is supposed to answer in plain language. "Active customers" means something specific to your system.
  • Output format: what columns the result should include, what order, and any grouping or aggregation.

Give the AI a compact version of the schema rather than the full DDL. A five-column summary of each relevant table is easier for the AI to use correctly than a hundred-line script with indexes and comments.

How to describe the query requirement

State the business question first, then the technical constraints. "Show me the total revenue by customer for orders placed in the last 90 days, excluding canceled orders" is more useful than "write a JOIN query." The AI can translate the business question into SQL; it cannot translate a vague technical description into the right business question.

  1. State what the query should return: the rows, the columns, and any filters.
  2. Name the tables and the join conditions if you know them.
  3. Specify any business rules: what "active" means, what date range applies, what status values to include or exclude.
  4. Note the target database: the SQL dialect matters. PostgreSQL, MySQL, and SQL Server have differences that affect function names and syntax.
  5. Ask the AI to explain its approach before or alongside the query so you can check its reasoning.

Verifying an AI-generated query

Never run an AI-generated query on production data without reviewing it first. Read the query for correctness, then run it on a sample or a test database.

  • Read the JOIN conditions: are they joining on the right columns? A wrong join can multiply rows silently.
  • Check the WHERE clause against the business rule. Does "active" match your definition?
  • Check for unintended Cartesian products: a missing JOIN condition produces one.
  • Verify that aggregate functions (SUM, COUNT, AVG) are applied to the right columns and grouped correctly.
  • Run the query on a small sample and check the row count and values against a known result.

If the result is wrong, describe what is wrong and ask the AI to correct it. Include the incorrect result and the expected result so the AI can identify the discrepancy.

How fenbs helps

Keep business definitions and schema notes with the queries

Add the project to fenbs. Write the business definitions — what "active customer" means, what the standard reporting period is — as AI context notes. Every developer and connected assistant working on the database reads the same definitions before writing a query.

Create a free account

Free for one person · No credit card · Works with Claude, ChatGPT, Cursor and more

Recording query decisions

Queries that answer recurring business questions deserve a decision record. When the team agrees on how to calculate retention, which status values count as "completed," or how to handle NULLs in a revenue report, record that decision. The next developer should not have to rediscover it.

A decision record for a query covers: the business question, the agreed answer, the key assumptions, and the date. If the business rule changes and the query must change with it, update the record. Two queries that answer the same question differently create confusion; a decision record makes the current answer explicit.

Iterating on a query that is almost right

Most AI-generated queries need at least one revision. When the first version is close but not correct, describe exactly what is wrong: which rows are appearing that should not be there, which aggregate is producing the wrong number, which filter is too broad or too narrow. A precise description of the error produces a more targeted fix than "this query is wrong."

If you find yourself correcting the same type of mistake repeatedly — the AI always joins on the wrong column, always forgets a status filter — add that correction to the business definition you supply. The next query starts from a description that already includes the rule, so the AI does not have to rediscover it.

How to do this with fenbs

  1. Create a free account and add a project for the database or reporting system.
  2. Write the business definitions as AI context notes: what each key term means, what the standard date ranges are, what status values are included in reports.
  3. Record the approved query decisions in Decisions and rules: the agreed formula for retention, the canonical revenue calculation, the filter rules.
  4. Connect your coding assistant to fenbs from Integrations. When it writes a query, it starts from the agreed definitions.
  5. When a query definition changes, update the decision and note what changed and why.

Questions people ask.

What should I include when asking an AI to write a SQL query?

The relevant table names and columns, the join conditions, the business definition of what you are filtering for, the target database dialect, and the expected output. The more precisely you describe the business question, the more useful the first draft will be.

How do I check whether an AI-generated query is correct?

Read the JOIN conditions, the WHERE clause, and the aggregate functions against the business rule. Then run the query on a small sample and compare the result to a known correct answer.

Can an AI write queries for any SQL database?

AI can write queries for major databases including PostgreSQL, MySQL, SQL Server, and SQLite. Specify the dialect in your request because syntax differences between databases affect functions like date arithmetic, string handling, and window functions.

What is the biggest risk when using AI to write SQL?

The biggest risks are incorrect JOIN conditions that multiply rows and WHERE clauses that do not match the intended business rule. Always run a generated query on a sample with a known result before using it on production data.

Should I store AI-generated queries?

Store queries that answer recurring questions and have been reviewed and approved. Keep the query, the business question it answers, and the assumptions it makes. When the business rule changes, update the query and the record.

More in Agent harness (for developers)

All Agent harness (for developers) articles

Start with one thing.

Free for one person · No credit card · Works with Claude, ChatGPT, Cursor and more

There is nothing to set up first. Write one line and you’ve started.