# Format SQL with an AI agent without changing its meaning

> Canonical: https://skillalmanac.com/learn/format-sql-with-an-ai-agent | Updated: 2026-11-26 | Index status: index-eligible

Format SQL with an AI agent, then look for changes in meaning: lint, fix, compare normalized versions and compare results on test data.

## Facts

- 2026-11-21: SQLFluff is a SQL linter; its documented fix command is `sqlfluff fix my_query.sql` (https://docs.sqlfluff.com/en/stable/)
- 2026-11-21: SQLFluff lists 25+ dialects and 70+ rules, and its docs page shows no command-line flags (https://docs.sqlfluff.com/en/stable/)
- 2026-11-26: SQLGlot is a Python parser and transpiler that supports over 30 dialects and exposes a pretty=True output option (https://github.com/tobymao/sqlglot)
- 2026-11-21: SQLFluff's configuration page sets the dialect with `dialect` under the `[sqlfluff]` section of `.sqlfluff`, and lists supported names with `sqlfluff dialects` (https://docs.sqlfluff.com/en/stable/configuration/setting_configuration.html)
- 2026-11-26: SQLGlot's README says generated output does not keep the original formatting, casing or quoting, and comments are kept only where the tool can manage it (https://github.com/tobymao/sqlglot)

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

1. 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.sql` to `my_query.original.sql`.
2. Install SQLFluff with `pip install sqlfluff`. Set the dialect in a `.sqlfluff` file in the project directory, under the `[sqlfluff]` section, for example `dialect = postgres`. Run `sqlfluff dialects` to 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.
3. Lint the original to see what the rules flag: `sqlfluff lint my_query.sql`.
4. 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.
5. 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.
6. 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 any `ORDER BY` clauses survived. If it prints anything else, stop and find the cause before going on.
7. Compare results on test data. Do this only for `SELECT` statements 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 an `ORDER 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`:

```sql
SELECT id,name, created_at FROM users
WHERE  created_at::date >= '2026-01-01' -- this year
ORDER BY id
```

With `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:

```sql
SELECT
    id,
    name,
    created_at
FROM users
WHERE created_at::date >= '2026-01-01' -- this year
ORDER BY id
```

The 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:

```python
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:

```sql
SELECT id, name, created_at FROM users WHERE CAST(created_at AS DATE) >= '2026-01-01' /* this year */ ORDER BY id
```

The 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 differs` after the date literal was changed in one file. It printed the same for a second test query with a join: SQLFluff's default rules rewrote `join customers c on c.id=o.customer_id` as `inner 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 with `ValueError: Unknown dialect 'sparksql'. Did you mean spark?`. A placeholder such as `your-dialect` fails the same way.
- **Unsupported statement.** For `VACUUM FULL users`, SQLGlot logged `contains unsupported syntax. Falling back to parsing as a 'Command'.` and kept most of the statement as raw text. A copy with lowercase keywords then printed `output differs`.
- **SQL that SQLFluff cannot parse.** `sqlfluff lint` printed a `PRS` line (`Couldn't find closing bracket for opening bracket.`), and `sqlfluff fix` left 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"` becoming `name`, in the raw diff.
- **A lint pass is not a meaning check.** SQLFluff's docs describe `fix` as 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 users` parsed as `mysql` came back as `SELECT 'Name' FROM users`, a string instead of a column. `SELECT id FROM t WHERE b ~ 'x'` parsed as `mysql` raised a parse error. The example query above parsed as `mysql` with 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 diff` or `diff` on 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](/skills/skill-almanac/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

- [sql-and-database-helper](https://skillalmanac.com/skills/skill-almanac/sql-and-database-helper.md): Platform Score 57/100 (provisional)

## Related guides

- [Optimize a SQL Query With an AI Agent: Start From the Plan](https://skillalmanac.com/learn/optimize-a-sql-query-with-an-ai-agent.md)
- [Plan a Database Migration with an AI Agent: Rollback Checks](https://skillalmanac.com/learn/plan-a-database-migration-with-an-ai-agent.md)
- [Rewrite a Paragraph with an AI Agent and Keep Its Facts](https://skillalmanac.com/learn/rewrite-a-paragraph-with-an-ai-agent.md)
- [How to Use AI in Marketing Without Unsupported Claims](https://skillalmanac.com/learn/how-to-use-ai-in-marketing.md)
- [How to Use an AI Agent on a First Task You Can Check](https://skillalmanac.com/learn/how-to-use-an-ai-agent.md)
- [Redact a PDF Without Leaving the Text Behind](https://skillalmanac.com/learn/redact-a-pdf-without-leaking-text.md)

## Sources

- https://docs.sqlfluff.com/en/stable/
- https://docs.sqlfluff.com/en/stable/configuration/setting_configuration.html
- https://github.com/tobymao/sqlglot

Platform Scores report our assessment under a published method. They are not a safety guarantee.
