Format SQL with an AI agent without changing its meaning
Format SQL with an AI agent, then look for changes in meaning: lint, fix, compare normalized versions and compare results on test data.
Updated · Markdown version
An AI agent can reformat a SQL query quickly, but a reformatted query should ship only after checks that would catch a change in meaning. The checks below use a linter to rewrite the layout, a parser to compare the two versions in a normalized form, and a run on test data. Passing them raises confidence. It does not prove that the two versions return the same results on every input.
Steps
- Save the original query to its own file and keep a copy, so you have a baseline to compare against. For example, copy
my_query.sqltomy_query.original.sql. - Install SQLFluff with
pip install sqlfluff. Set the dialect in a.sqlflufffile in the project directory, under the[sqlfluff]section, for exampledialect = postgres. Runsqlfluff dialectsto list the names it accepts and use the one your database runs. This guide sets the dialect in the file; the configuration page points to the CLI reference for command-line options. - Lint the original to see what the rules flag:
sqlfluff lint my_query.sql. - Apply the fixes:
sqlfluff fix my_query.sql. Then lint again. A clean second pass means the enabled rules are satisfied, not that the query returns the same rows. - Install SQLGlot with
pip install sqlglot. Parse both versions in the same dialect, generate a string from each and compare the strings. The script is shown under "Example run" below. - If the script prints
same output, diff the two raw files and read the diff line by line. Check that comments, string literals, identifier quoting and anyORDER BYclauses survived. If it prints anything else, stop and find the cause before going on. - Compare results on test data. Do this only for
SELECTstatements you have reviewed and found read-only. Run both versions on a disposable copy of the database, against the same data snapshot and with the same parameter values. Compare how many times each row appears, not only which rows appear. Compare row order when the query has anORDER BY. When it has none, do not compare the two listings line by line; sort both first. Statements that change data or schema need a separate check of the resulting state and side effects, each version on its own fresh copy.
Step 7 is a workflow recommendation of this guide, not something SQLFluff's or SQLGlot's docs prescribe.
Example run
The outputs below come from SQLFluff 4.5.0 and SQLGlot 30.35.0 on Python 3.11, run on 2026-11-26. Other versions may print different text.
The example query is PostgreSQL, saved as my_query.sql and copied to my_query.original.sql:
SELECT id,name, created_at FROM users
WHERE created_at::date >= '2026-01-01' -- this year
ORDER BY idWith dialect = postgres in .sqlfluff, sqlfluff lint my_query.sql reported three violations (LT09 once, LT01 twice). After sqlfluff fix my_query.sql the second lint was clean and the file read:
SELECT
id,
name,
created_at
FROM users
WHERE created_at::date >= '2026-01-01' -- this year
ORDER BY idThe comparison script for step 5 reads both files as UTF-8, so it behaves the same on Windows, where Python's default file encoding may not be UTF-8:
from pathlib import Path
import sqlglot
from sqlglot.errors import SqlglotError
DIALECT = "postgres" # SQLGlot's name for the dialect; change it to match your database
def normalized(path):
sql = Path(path).read_text(encoding="utf-8")
return sqlglot.parse_one(sql, dialect=DIALECT).sql(dialect=DIALECT)
try:
a = normalized("my_query.original.sql")
b = normalized("my_query.sql")
except SqlglotError as err:
print("could not parse:", err)
else:
print("same output" if a == b else "output differs")For the two files above it printed same output. Both versions normalized to this string:
SELECT id, name, created_at FROM users WHERE CAST(created_at AS DATE) >= '2026-01-01' /* this year */ ORDER BY idThe dialect is set in two places, and each tool has its own list of names. Change dialect in .sqlfluff and DIALECT in the script together.
| Database | SQLFluff name | SQLGlot name |
|---|---|---|
| PostgreSQL | postgres | postgres |
| MySQL | mysql | mysql |
| SQL Server | tsql | tsql |
| Spark SQL | sparksql | spark |
What the other outcomes looked like in the same run:
- Output differs. The script printed
output differsafter the date literal was changed in one file. It printed the same for a second test query with a join: SQLFluff's default rules rewrotejoin customers c on c.id=o.customer_idasinner join customers as c on o.customer_id = c.id, which is more than layout. - Could not parse. With an unclosed bracket in one file, the script printed
could not parse: Expecting ). Line 1, Col: 60.followed by the query text. This is not a match. Fix the SQL or the dialect name and run it again. - Unknown dialect name.
DIALECT = "sparksql"stopped the script withValueError: Unknown dialect 'sparksql'. Did you mean spark?. A placeholder such asyour-dialectfails the same way. - Unsupported statement. For
VACUUM FULL users, SQLGlot loggedcontains unsupported syntax. Falling back to parsing as a 'Command'.and kept most of the statement as raw text. A copy with lowercase keywords then printedoutput differs. - SQL that SQLFluff cannot parse.
sqlfluff lintprinted aPRSline (Couldn't find closing bracket for opening bracket.), andsqlfluff fixleft the file unchanged.
Check that it worked: the second lint is clean, the script prints same output, the raw diff contains only formatting changes your SQLFluff rules are expected to make, and the step 7 comparison shows the same rows the same number of times. Matching strings and equal results on one test dataset raise confidence. They do not prove the two queries are equivalent on all inputs.
Pitfalls
- Comments disappear or move. SQLGlot does not promise to keep every comment, so do not treat its output as the file to save. Use it only as a comparator and look at the comments in the raw diff yourself.
- A matching string is not a meaning check. SQLGlot's README says it preserves the meaning of a query rather than its exact text and that cosmetic details can change, so a match shows only that the two parse trees print the same. Check quoting and identifier case, such as
"Name"becomingname, in the raw diff. - A lint pass is not a meaning check. SQLFluff's docs describe
fixas automatically correcting many lint violations, and they do not say the corrections preserve query meaning, so the row comparison in step 7 is still needed. - Wrong dialect. SQLGlot's README says to pass the source dialect whenever you know it. In SQLGlot 30.35.0, the PostgreSQL query
SELECT "Name" FROM usersparsed asmysqlcame back asSELECT 'Name' FROM users, a string instead of a column.SELECT id FROM t WHERE b ~ 'x'parsed asmysqlraised a parse error. The example query above parsed asmysqlwith no error at all, so a wrong dialect is not always reported. Use the dialect your database runs. - The agent edits more than formatting. An agent asked to "format" may also rename aliases or reorder joins. Run
git diffordiffon the saved files before accepting anything.
When to use a skill instead
A one-off format request can be handled with a single prompt, but a repeatable check is easier to run when the agent knows the rules up front. If you review SQL in many queries, a skill that fixes the workflow above is more consistent than retyping the steps. sql-and-database-helper covers the SQL review side of this task, including writing, checking and migrating queries for PostgreSQL, MySQL and SQLite. Per its listing, it is read-only by default, which fits a review pass where you do not want the agent writing to a database. It does not replace the lint and row comparison above, so use it for the review and keep the checks as separate steps.
FAQ
Does a formatter change what a query returns? SQLFluff's docs do not say that fixes preserve query meaning, so a changed result is possible in principle. A passing lint does not show the results match, so compare the parsed output and run both versions on test data. Those checks raise confidence. They do not prove the results match on every input.
Does SQLGlot keep my comments when it formats? Its README gives no promise of full comment retention, so some may be moved or dropped, and a moved comment makes step 5 report a difference. Keep the original file and compare comments in the raw diff.
Which SQL dialect should the check use? Use the dialect your database engine runs, under the name each tool gives it. SQLGlot reads and writes many dialects and recommends naming the source and target explicitly, so a mismatch is a common source of false results. The names can differ between tools: Spark SQL is sparksql in SQLFluff and spark in SQLGlot.
Related skills in this catalog
Platform Score is our assessment under a published method. It is not a safety guarantee.
Related guides
- Optimize a SQL Query With an AI Agent: Start From the Plan
- Plan a Database Migration with an AI Agent: Rollback Checks
- Rewrite a Paragraph with an AI Agent and Keep Its Facts
- How to Use AI in Marketing Without Unsupported Claims
- How to Use an AI Agent on a First Task You Can Check
- Redact a PDF Without Leaving the Text Behind
Sources
- https://docs.sqlfluff.com/en/stable/ (accessed 2026-11-26)
- https://docs.sqlfluff.com/en/stable/configuration/setting_configuration.html (accessed 2026-11-26)
- https://github.com/tobymao/sqlglot (accessed 2026-11-26)