How to Use SQL Generators Effectively

How to describe a schema so generated SQL is right, and what to check before running it.

5 min read

Give the schema, not a description of it

Paste the actual CREATE TABLE statements or a column list with types. Generators guess column names otherwise, and a query against guessed names either errors or, worse, silently matches the wrong column.

Say which database engine you use. Date functions, string concatenation, limit syntax and window function support all differ between PostgreSQL, MySQL, SQL Server and SQLite.

Be exact about the question

Ambiguity in the request becomes ambiguity in the join. "Customers with orders last month" leaves open whether to count customers with zero orders, whether "last month" is calendar or rolling, and which timezone applies.

State the expected shape of the result: which columns, what granularity, how to sort, whether duplicates are possible.

Verify before running

Read the joins first. An inner join where a left join was needed silently drops rows and is the most common generated-SQL bug.

Check aggregation: every non-aggregated column should appear in GROUP BY, and a join that fans out rows will inflate SUM results.

Run against a copy or with a LIMIT first, and compare the row count to what you expected.

Never run these unreviewed

Anything with DELETE, UPDATE, DROP or TRUNCATE. Wrap them in a transaction you can roll back, and run the equivalent SELECT first to see exactly which rows are affected.

Queries on production during business hours without an execution plan check. A generated query with a missing index can lock up a table.

Frequently asked questions

Tool for this

CodeGPTGenerate, explain, review and debug code.

Open the CodeGPT page

More in Developer Tools & Code