sqlfluff — SQL linter/fixer, measured on 4.5.0
sqlfluff (sqlfluff/sqlfluff, licence MIT — the wheel's license block reads "Copyright (c) 2018-2026 Alan Cruickshank") is the rule-based SQL linter with dialect-aware parsing (28 dialects, all derived from ansi except soql). Everything here is original text measured live on 4.5.0 — the newest release at the time of writing (matched on PyPI and conda-forge: 4.5.0 in both, so pip install sqlfluff==4.5.0 and conda install -c conda-forge sqlfluff agree) — with python -m pip index versions sqlfluff as the drift check. It needs Python ≥ 3.10. The optional native engine ships as the rs extra (pip install "sqlfluff[rs]" pulls sqlfluffrs==4.5.0; it is imported opportunistically, no config key selects it).
Command surface and exit codes
Only 8 subcommands exist: lint, fix, format, parse, render, dialects, rules, version. sqlfluff config does not exist — older guides show it; on 4.5 you get Error: No such command 'config'.
Exit codes measured unpiped, per command:
| situation | lint | fix | parse |
|---|---|---|---|
| clean / everything applied | 0 | 0 | 0 |
| violations or parse/templating errors | 1 | 1 only if unfixable violations remain | 1 |
| User Error (unknown dialect, missing path, invalid config) | 2 | 2 | 2 |
The sharp asymmetry: fix returns 0 on a file with a parse error (it just fixes nothing — the unparsable section counts as one "unfixable" violation listed in [brackets]) but 1 on fixable-in-theory rules that no fix exists for (e.g. AM04 on SELECT * FROM tbl — rc 1, file untouched). A templater misconfiguration is not a User Error at all: --templater placeholder without param_style dies with an uncaught ValueError traceback, rc 1 (both for lint and render). fix --check asks [Y/n] interactively; on EOF in a non-interactive run it crashes with a click traceback — never put --check in a pipeline.
Reading violations
Violations print as L: line | P: col | CODE | message [rule.name] under a == [path] FAIL header, always followed by All Finished! (even on rc 1). Parse errors carry the code PRS (leading space), embed the parser's expectation, and add the WARNING Parsing errors found and dialect is set to '<dialect>'. Have you configured your dialect correctly?. Clean files print nothing — there is no PASS marker, so an empty directory run yields only All Finished! (rc 0). Output is ANSI-free when piped (auto-detect, unlike several linters); force with -n/--nocolor.
fix mechanics
- Since 3.0 applying fixes is the default;
-f/--forceis deprecated and a no-op. Default run writes files in place (rc 0 with everything applied). - Files with parse or templating errors are not fixed unless
--FIX-EVEN-UNPARSABLE(exact uppercase spelling) is passed — on the CLI or asfix_even_unparsable = truein config.--ignore parsingandnoqamerely hide the error; they do not enable fixing. A parse-error file exits rc 0 from fix (nothing fixable — the unparsable section just counts as one "unfixable" violation in[brackets]), while a file whose only remaining violations have no fix (AM04onSELECT * FROM tbl) exits rc 1 after applying whatever elsewhere is fixable — measured: a newline-less file still gainedLT12's trailing newline ([file] FIXED+[1 unfixable linting violations found]). Partial fix, rc 1. -x/--fixed-suffix NAMEwrites the fixed copy to<basename><NAME>with no separator:report.sql -x fixed→reportfixed.sql(the original stays untouched — measured; nothing inserts the_you would expect).fix -(stdin) prints the fixed SQL to stdout rc 0 without touching disk — a pipeline-safe formatter:cat q.sql | sqlfluff fix -d sqlite - > q_fixed.sql.formatis the reflow-only sibling: it applies layout, not semantic, rules (measured:SELECT * FROM tblstayed untouched underformat, rc 0) — use it when you want whitespace/indentation changes only.--rules/-r,--exclude-rules/-etake comma-separated codes; rules narrow the allowlist.
Config discovery — later overwrites earlier
Files discovered per directory, in this order (later wins on a colliding key): setup.cfg, tox.ini, pep8.ini, .sqlfluff, pyproject.toml ([tool.sqlfluff.core]). Measured: in a directory with both .sqlfluff (exclude_rules = LT09) and pyproject.toml (exclude_rules = ["LT01"]), the TOML value replaced the ini value — LT09 violations came back, neither file's list merged. Values do not merge across files or directories either: a nearer .sqlfluff replaces the whole value of a colliding key (measured with parent/sub exclude_rules).
- CLI flags > config files;
--config <file>(INI format required) adds another layer;--ignore-local-configdrops file discovery. - User-level directory on Linux:
~/.config/sqlfluff(queried first), then platformdirs'user_config_dir, which honours$XDG_CONFIG_HOME/sqlfluff. SQLFLUFF_DIALECTand friends are inert: in a directory with no config,SQLFLUFF_DIALECT=sqlite sqlfluff lint x.sqlfails rc 2 withNo dialect was specified— 4.5's config loader reads noSQLFLUFF_*variables (the only environment variable consulted isXDG_CONFIG_HOME). Any guide instructing env-var config is stale here.- No dialect anywhere → rc 2
User Error: No dialect was specified...including the full dialects list — a convenientdialects-command shortcut. - An invalid layout option in any
.sqlfluffis rejected fail-closed rc 2 before linting: layout options are only valid undersqlfluff:layout:type:<type>([sqlfluff:layout] type_of_comma = ...-era spelling is now a User Error naming the valid shape). Valid keys per type, from the validator source:spacing_before,spacing_after,spacing_within,line_position,align_within,align_scope,keyword_line_position,keyword_line_position_exclusions,alignment_coordinate_space. Bad enum values, non-integermax_parse_depth/max_parse_nodes/runaway_limit(all under[sqlfluff], defaults 600 / 100000 / 10,0disables the parse guards) are likewise rc 2. - Deprecated rule-era keys are auto-translated with a WARNING (printed twice, to stderr):
[sqlfluff:rules] comma_style = leadingmaps tolayout:type:comma:line_positionand takes effect for the run — migrate the key anyway, the warning says it "will be removed in a later release".
Rule selection — the fail-open trap
--rules XX99 produces only a stderr WARNING (Tried to allowlist unknown rule references: ['XX99']) and proceeds: the remaining (unknown-matching) codes are skipped. Consequences, all measured:
- A typo in a single allowlist code degrades silently —
--rules XX99,LT09still enforces onlyLT09(rc 1 with the warning on stderr). - A typo that kills every code (
--rules XX99on a violating file) exits rc 0. CI pipelines that grep rc only will pass on a broken allowlist. - The same for legacy aliases:
L1,XX99— both unknown, both warned. sqlfluff ruleslists all 79 rule codes in 10 families (LT layout 15, CV convention 13, ST structure 12, AL aliases 10, AM ambiguous/annoyances 9, RF referencing 7, TQ templating 4, CP capitalisation 5, PG/JJ/OR dialect specials) with their legacyL0xxaliases on each line; it takes no positional filter (sqlfluff rules LT01→ rc 2).-vvvvprints the fuller detail per rule.
Rule configuration lives in [sqlfluff:rules:<config_ref>] keyed by the rule-class slug — not by the code. [sqlfluff:rules:LT01] sections are silently inert apart from a two-line warning that names the right section (Rule configuration contain a section for unexpected rule 'LT01'. These values will be ignored. / ... will be specified in 'sqlfluff:rules:layout.spacing'). Time-saver: every violation line's trailing [layout.spacing] bracket is the config section name you can copy. LT01 itself reads only layout config (its docstring: the sqlfluff.layout section is how you tweak it), so spacing knobs live at sqlfluff:layout:type:*, not under the rule.
Templaters — where most debugging time goes
Default templater is jinja; choices are raw|jinja|python|placeholder (-t or [sqlfluff] templater = ...). Measured behaviors on 4.5:
- Selecting the templater takes a flag or the core key: setting only
[sqlfluff:templater:placeholder]in the config leavesjinjaactive (a:tableplaceholder then hits the parser as literal SQL →PRS). Add-t placeholderortemplater = placeholderunder[sqlfluff]. - Jinja has the dbt builtins without dbt:
{{ ref("x") }}renders to the placeholder table namex;{{ var('foo', 'bar') }}renders its default. An undefined Jinja variable renders as empty — no templating error — so the damage surfaces as a downstream parse error (SELECT {{ x }} FROM t→PRSonSELECT). --templater rawleaves{{ ... }}verbatim; that hits the parser and PRS-fails. Userawonly for genuinely plain SQL.- The placeholder templater requires
param_style(or a customparam_regex; the two are mutually exclusive) — without either it raises the uncaughtValueError(rc 1 traceback). The 13 style names:colon,colon_optional_quotes,colon_nospaces,numeric_colon,pyformat,dollar,databricks,dollar_surround,flyway_var,question_mark,numeric_dollar,percent,ampersand. Placeholder values are flat keys in the same section ([sqlfluff:templater:placeholder] param_style = colon+table = my_tablerendersFROM :table→FROM my_table); a parameter with no supplied value silently substitutes its own name (:table→table), never errors. --ignore templatingsuppresses the templating-born failures: a Jinja file whose render produced unparsable SQL exits rc 0 with-i templating(measured), while--ignore parsingdrops the PRS lines but ordinary rules can still flag fragments of the unparsable region.parseprints the position-annotated parse tree ([L: 1, P: 1]tables withunparsable: !!lines);renderprints the templated SQL (--templater rawechoes the file verbatim).
noqa
- Line disable: bare
-- noqa, or code list-- noqa: LT01,LT09, or section control-- noqa: disable=LT04...-- noqa: enable=LT04(exact codes; measured). - A family prefix does not work:
disable=LTleftLT04firing on the covered lines — only full codes disable. --disable-noqaignores every noqa comment (find the underlying violations);--disable-noqa-except LT09keeps only that code's comments;--warn-unused-ignoresflags dead comments.- Directory runs skip files per-directory
.sqlfluffignore(gitignore-style names); only*.sqlfiles are candidates (a sibling.pyis simply not linted);--disregard-sqlfluffignoresoverrides.
Recipes
Install and verify (venv, pinned, cross-checked dialect count):
python3 -m venv "$HOME/.venvs/sqlfluff-probe" 2>/dev/null ||
python3 -m venv --upgrade-deps "$HOME/.venvs/sqlfluff-probe"
"$HOME/.venvs/sqlfluff-probe/bin/pip" install -q "sqlfluff==4.5.0"
V="$HOME/.venvs/sqlfluff-probe/bin/sqlfluff"
[ "$($V version)" = "4.5.0" ] || { echo "version drift"; exit 1; }
[ "$($V dialects 2>/dev/null | grep -cE '^ansi:')" -eq 1 ] &&
echo "ok install"
Exit-code matrix, unknown-rule fail-open, User-Error class (run rc checks unpiped):
cd "$(mktemp -d)"
V="$HOME/.venvs/sqlfluff-probe/bin/sqlfluff"
printf 'SELECT a\nFROM tbl\n' > clean.sql
printf 'select a,b\nfrom tbl\n' > messy.sql
$V lint -d sqlite clean.sql >/dev/null 2>&1; [ $? -eq 0 ] || exit 1
$V lint -d sqlite messy.sql >/dev/null 2>&1; [ $? -eq 1 ] || exit 1
$V lint -d nosuchdb messy.sql >/dev/null 2>&1; [ $? -eq 2 ] || exit 1
# a typo'd allowlist turns a violating file into rc 0 (stderr warning only)
out="$($V lint -d sqlite --rules XX99 messy.sql 2>&1)"; rc=$?
[ "$rc" -eq 0 ] || exit 1
printf '%s' "$out" | grep -q "unknown rule references" || exit 1
echo "ok exit-codes"
fix matrix: in-place apply, glued suffix name, unfixable rc 1, stdin stdout mode:
cd "$(mktemp -d)"
V="$HOME/.venvs/sqlfluff-probe/bin/sqlfluff"
printf 'select a,b\nfrom tbl\n' > q1.sql
$V fix -d sqlite q1.sql >/dev/null 2>&1; [ $? -eq 0 ] || exit 1
printf '%s' "$(cat q1.sql)" | grep -q $' b' || exit 1
printf 'select a,b\nfrom tbl\n' > q2.sql
$V fix -d sqlite -x fixed q2.sql >/dev/null 2>&1
[ -f q2fixed.sql ] || exit 1 # no underscore, original kept
grep -q 'select a,b' q2.sql || exit 1
printf 'SELECT * FROM tbl\n' > q3.sql
$V fix -d sqlite q3.sql >/dev/null 2>&1; [ $? -eq 1 ] || exit 1 # AM04 unfixable
[ "$(cat q3.sql)" = "SELECT * FROM tbl" ] || exit 1
fixed="$(printf 'select 1 from tbl' | $V fix -d sqlite -)"
[ "$fixed" = "select 1 from tbl" ] && echo "ok fix-matrix"
Config precedence + placeholder templater through config:
cd "$(mktemp -d)"
V="$HOME/.venvs/sqlfluff-probe/bin/sqlfluff"
printf 'select a,b\nfrom tbl\n' > m.sql
printf '[sqlfluff]\ndialect = sqlite\nexclude_rules = LT09\n' > .sqlfluff
printf '[tool.sqlfluff.core]\ndialect = "sqlite"\nexclude_rules = ["LT01"]\n' > pyproject.toml
out="$($V lint -d sqlite -n m.sql 2>&1)"
printf '%s' "$out" | grep -q LT09 || exit 1 # pyproject REPLACED .sqlfluff's list
printf '%s' "$out" | grep -q LT01 && exit 1
printf 'SELECT 1 FROM :table\n' > ph.sql
printf '[sqlfluff]\ndialect = sqlite\ntemplater = placeholder\n[sqlfluff:templater:placeholder]\nparam_style = colon\ntable = my_table\n' > ph.conf
$V lint --config ph.conf -n ph.sql >/dev/null 2>&1; [ $? -eq 0 ] || exit 1
echo "ok config-precedence"
noqa + config-section validity (inert bare-code section warns, block disable works):
cd "$(mktemp -d)"
V="$HOME/.venvs/sqlfluff-probe/bin/sqlfluff"
printf '[sqlfluff]\ndialect = sqlite\n[sqlfluff:rules:LT01]\nanything = true\n' > .sqlfluff
printf 'select a,b \nfrom tbl\n' > n.sql
out="$($V lint -n n.sql 2>&1)"
printf '%s' "$out" | grep -q "unexpected rule 'LT01'" || exit 1
printf '[sqlfluff]\ndialect = sqlite\n' > .sqlfluff
printf 'select a\n-- noqa: disable=LT04\n,b\n-- noqa: enable=LT04\nfrom tbl\n' > b.sql
out="$($V lint -n b.sql 2>&1)"
printf '%s' "$out" | grep -q LT04 && exit 1 # covered lines disabled
printf '%s' "$out" | grep -q LT02 || exit 1 # other rules still fire
echo "ok noqa"
Version honesty
All of the above was measured on 4.5.0 (pip wheel, newest PyPI and conda-forge release on the writing day; no older line probed). SQLFluff releases roughly monthly and has a history of semantically-visible CLI changes (config subcommand removed, -f deprecated in 3.0, layout config reshaped in 3.x, SQLFLUFF_* envs gone) — the 3.x/2.x compatibility notes in the measured facts above are exactly the paths that bite when someone runs an older or newer copy. Re-probe sqlfluff version, the exit-code matrix and the placeholder contract before quoting them to a stranger on a different version.