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.
- State what the query should return: the rows, the columns, and any filters.
- Name the tables and the join conditions if you know them.
- Specify any business rules: what "active" means, what date range applies, what status values to include or exclude.
- Note the target database: the SQL dialect matters. PostgreSQL, MySQL, and SQL Server have differences that affect function names and syntax.
- 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.
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 accountFree 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
- Create a free account and add a project for the database or reporting system.
- 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.
- Record the approved query decisions in Decisions and rules: the agreed formula for retention, the canonical revenue calculation, the filter rules.
- Connect your coding assistant to fenbs from Integrations. When it writes a query, it starts from the agreed definitions.
- When a query definition changes, update the decision and note what changed and why.