Pirate Quick Guides
All guides

SQLFluff

SQL linter & formatter

v4.5.0 Written for SQLFluff 4.5.0, released 30 Oct 2026Checked 23 Nov 2026
  • 79 rules in 4.5.0 across 11 groups, including dialect-only PG (Postgres) and TQ (T-SQL) rules.
  • Newer rules: AM09, CV12, CV13, LT14, LT15, RF07, ST09–ST12, OR01, PG01–PG02, TQ02–TQ04.
  • Off by default: AL07, CV13, RF07, PG01, PG02, TQ04 (enable with force_enable = True).
  • Legacy L0xx codes still work as aliases in --rules, config and noqa.

A dialect-aware SQL linter and auto-formatter (Python). It parses your SQL, checks it against style and correctness rules, and fixes most of them for you, including Jinja and dbt templated SQL.

Works withdbtJinjapre-commitGitHub ActionsVS Code

79 rules

layout, aliasing, structure…

Auto-fix

fix and format rewrite files

28 dialects

Postgres, BigQuery, Snowflake…

Templating

Jinja, dbt, placeholders

Quick start

uv tool install sqlfluffprintf "[sqlfluff]\ndialect = postgres\n" > .sqlfluffsqlfluff lint .sqlfluff fix .
  • Install
  • Install as a global tool (or pipx install)
  • Run without installing
  • dbt templater (plus your dbt adapter)
  • Show the installed version
  • Lint a folder
  • Lint one file
  • Lint stdin
  • Only some rules
  • A rule group
  • Skip rules
  • json · yaml · sarif · gitlab · github-annotation-native
  • All CPUs (-1: all but one)
  • Always exit 0 (rollout)

Output (abridged)

== [q.sql] FAILL:  1 | P:  1 | LT09  Select targets should  be on a new line…L:  2 | P:  9 | CV05  Comparisons with NULL  should use "IS".L = line · P = position
  • Fix in place
  • Fix only some rules
  • Confirm before writing
  • Write q_fixed.sql instead
  • Also list what’s left
  • stdin → stdout
  • Format with a fixed set of stable rules

Before → after fix

-- beforeselect a,b as c from foo fwhere a = null-- afterselect    a,    b as cfrom foowhere a is null

format ignores --rules, but still respects --exclude-rules and config.

  • Parse tree (-c code only, -f yaml)
  • SQL after Jinja / dbt rendering
  • Every rule with groups & aliases
  • All supported dialects
  • Verbose output
  • Debug which config is used
  • Required: there is no default
  • Default (also dbt · python · placeholder · raw)
  • Default 80
  • Turn rules off
  • Only these rules (default: all)
  • Report, but don’t fail
  • Leading commas ([sqlfluff:layout:type:comma])
  • Rule options use the rule name, not the code

.sqlfluff

[sqlfluff]dialect = postgresmax_line_length = 100exclude_rules = AL07, ST06[sqlfluff:indentation]tab_space_size = 4[sqlfluff:layout:type:comma]line_position = leading[sqlfluff:rules:capitalisation.keywords]capitalisation_policy = upper

Config cascades: home dir → project root → each subfolder. Also read from setup.cfg, tox.ini and pyproject.toml ([tool.sqlfluff.core]).

  • Ignore every rule on this line
  • Ignore some rules on this line
  • Disable from here on…
  • …and enable again (all works too)
  • Ignore files and folders (gitignore syntax)
  • Don’t fail on parsing (or templating) errors
  • Flag noqa comments that do nothing
  • Ignore all noqa comments
  • Default: Jinja
  • dbt projects (needs sqlfluff-templater-dbt)
  • :name, ?, $1… via param_style
  • Python format strings: {table}
  • Jinja macros
  • Values for template variables

.sqlfluff

[sqlfluff:templater:jinja]load_macros_from_path = macros/[sqlfluff:templater:jinja:context]schema = analytics# with templater = dbt[sqlfluff:templater:dbt]project_dir = .profiles_dir = ~/.dbttarget = dev
  • Inline annotations on GitHub PRs
  • Upload to code scanning
  • Lint only changed files

.pre-commit-config.yaml

repos:  - repo: https://github.com/sqlfluff/sqlfluff    rev: 4.5.0    hooks:      - id: sqlfluff-lint      - id: sqlfluff-fix

Rule code prefixes

  • Aliasing
  • Ambiguous
  • Capitalisation
  • Convention
  • Jinja
  • Layout
  • References
  • Structure
  • Oracle · Postgres · T-SQL only

28 dialects

ansi        athena      bigqueryclickhouse  databricks  db2doris       duckdb      exasolflink       greenplum   hiveimpala      mariadb     materializemysql       oracle      postgresredshift    snowflake   soqlsparksql    sqlite      starrocksteradata    trino       tsqlvertica

Select rules by code (LT01), name (layout.spacing), group (core) or legacy code (L001).

Aliasing

How tables and columns are aliased.

AL01aliasing.tablefixable

Implicit/explicit aliasing of table.

✗ Anti-pattern
SELECT    voo.aFROM foo voo
✓ Best practice
SELECT    voo.aFROM foo AS voo
aliasing = explicit
  • Legacy code: L011
AL02aliasing.columncorefixable

Implicit/explicit aliasing of columns.

✗ Anti-pattern
SELECT    a alias_colFROM foo
✓ Best practice
SELECT    a AS alias_colFROM foo
aliasing = explicit
  • Legacy code: L012
AL03aliasing.expressioncore

Column expression without alias. Use explicit AS clause.

✗ Anti-pattern
SELECT    sum(a),    sum(b)FROM foo
✓ Best practice
SELECT    sum(a) AS a_sum,    sum(b) AS b_sumFROM foo
allow_scalar = True
  • Set allow_scalar = False to also flag a lone expression.
  • Legacy code: L013
AL04aliasing.unique.tablecore

Table aliases should be unique within each clause.

✗ Anti-pattern
SELECT    t.a,    t.bFROM foo AS t, bar AS t-- This can also happen when using schemas where the-- implicit alias is the table name:SELECT    a,    bFROM    2020.foo,    2021.foo
✓ Best practice
SELECT    f.a,    b.bFROM foo AS f, bar AS b-- Also use explicit aliases when referencing two tables-- with the same name from two different schemas.SELECT    f1.a,    f2.bFROM    2020.foo AS f1,    2021.foo AS f2
  • Legacy code: L020
AL05aliasing.unusedcorefixable

Tables should not be aliased if that alias is not used.

✗ Anti-pattern
SELECT    aFROM foo AS zoo
✓ Best practice
SELECT    zoo.aFROM foo AS zoo-- Alternatively...SELECT    aFROM foo
alias_case_check = dialect
  • Legacy code: L025
AL06aliasing.lengthcoreopt-in

Enforce table alias lengths in from clauses and join conditions.

✗ Anti-pattern
SELECT    SUM(o.amount) as order_amountFROM orders as o
✓ Best practice
SELECT    SUM(orders.amount) as order_amountFROM ordersSELECT    replacement_orders.amount,    previous_orders.amountFROM    orders AS replacement_ordersJOIN    orders AS previous_orders    ON replacement_orders.id = previous_orders.replacement_id
min_alias_length = Nonemax_alias_length = None
  • Does nothing until min_alias_length or max_alias_length is set.
  • Legacy code: L066
AL07aliasing.forbidfixableopt-in

Avoid table aliases in from clauses and join conditions.

✗ Anti-pattern
SELECT    COUNT(o.customer_id) as order_amount,    c.nameFROM orders as oJOIN customers as c on o.id = c.user_id
✓ Best practice
SELECT    COUNT(orders.customer_id) as order_amount,    customers.nameFROM ordersJOIN customers on orders.id = customers.user_id-- Self-join will not raise issueSELECT    table1.a,    table_alias.bFROM    table1    LEFT JOIN table1 AS table_alias ON        table1.foreign_key = table_alias.foreign_key
force_enable = False
  • Off by default: enable with force_enable = True.
  • Legacy code: L031
AL08aliasing.unique.columncore

Column aliases should be unique within each clause.

✗ Anti-pattern
SELECT    a as foo,    b as fooFROM tbl;-- This can also happen when referencing the same column-- column twice, or aliasing an expression to the same-- name as a column:SELECT    foo,    foo,    a as fooFROM tbl;
✓ Best practice
SELECT    a as foo,    b as barFROM tbl;-- Avoid also using the same column twice unless aliased:SELECT    foo as foo1,    foo as foo2,    a as foo3FROM tbl;
AL09aliasing.self_alias.columncorefixable

Column aliases should not alias to itself, i.e. self-alias.

✗ Anti-pattern
SELECT    col AS col,    "Col" AS "Col",    COL AS colFROM table;
✓ Best practice
SELECT    col,    "Col"    COL,FROM table;-- Re-casing aliasing is still allowed where necessary, i.e.SELECT    col as "Col",    "col" as "COL"FROM table;
AL10aliasing.requiredcore

Derived tables must have an alias.

✗ Anti-pattern
SELECT *FROM (    SELECT 1 AS a)
✓ Best practice
SELECT *FROM (    SELECT 1 AS a) AS derived

Ambiguous

Code that works but hides intent.

AM01ambiguous.distinctcore

Ambiguous use of 'DISTINCT' in a 'SELECT' statement with 'GROUP BY'.

✗ Anti-pattern
SELECT DISTINCT    aFROM fooGROUP BY a
✓ Best practice
SELECT DISTINCT    aFROM foo
  • Legacy code: L021
AM02ambiguous.unioncorefixableopt-in

'UNION [DISTINCT|ALL]' is preferred over just 'UNION'.

✗ Anti-pattern
SELECT a, b FROM table_1UNIONSELECT a, b FROM table_2
✓ Best practice
SELECT a, b FROM table_1UNION DISTINCTSELECT a, b FROM table_2
  • Only for dialects with UNION DISTINCT: ansi, bigquery, clickhouse, databricks, db2, hive, mysql, redshift, snowflake, trino.
  • Legacy code: L033
AM03ambiguous.order_byfixable

Ambiguous ordering directions for columns in order by clause.

✗ Anti-pattern
SELECT    a, bFROM fooORDER BY a, b DESC
✓ Best practice
SELECT    a, bFROM fooORDER BY a ASC, b DESC
  • Legacy code: L037
AM04ambiguous.column_count

Query produces an unknown number of result columns.

✗ Anti-pattern
WITH cte AS (    SELECT * FROM foo)SELECT * FROM cteUNIONSELECT a, b FROM t
✓ Best practice
WITH cte AS (    SELECT * FROM foo)SELECT a, b FROM cteUNIONSELECT a, b FROM t
  • Legacy code: L044
AM05ambiguous.joinfixable

Join clauses should be fully qualified.

✗ Anti-pattern
SELECT    fooFROM barJOIN baz;
✓ Best practice
SELECT    fooFROM barINNER JOIN baz;
fully_qualify_join_types = inner
  • fully_qualify_join_types: inner (default), outer or both.
  • Legacy code: L051
AM06ambiguous.column_referencescore

Inconsistent column references in 'GROUP BY/ORDER BY' clauses.

✗ Anti-pattern
SELECT    foo,    bar,    sum(baz) AS sum_valueFROM fake_tableGROUP BY    foo, 2;-- The same also applies to column-- references in ORDER BY clauses.SELECT    foo,    barFROM fake_tableORDER BY    1, bar;
✓ Best practice
-- GROUP BY: ExplicitSELECT    foo,    bar,    sum(baz) AS sum_valueFROM fake_tableGROUP BY    foo, bar;-- ORDER BY: ExplicitSELECT    foo,    barFROM fake_tableORDER BY    foo, bar;-- GROUP BY: ImplicitSELECT    foo,    bar,    sum(baz) AS sum_valueFROM fake_tableGROUP BY    1, 2;-- ORDER BY: ImplicitSELECT    foo,    barFROM fake_tableORDER BY    1, 2;
group_by_and_order_by_style = consistent
  • Legacy code: L054
AM07ambiguous.set_columns

Queries within set query produce different numbers of columns.

✗ Anti-pattern
WITH cte AS (    SELECT        a,        b    FROM foo)SELECT * FROM cteUNIONSELECT    c,    d,    e FROM t
✓ Best practice
WITH cte AS (    SELECT a, b FROM foo)SELECT    a,    bFROM cteUNIONSELECT    c,    dFROM t
  • Legacy code: L068
AM08ambiguous.join_conditionfixable

Implicit cross join detected.

✗ Anti-pattern
SELECT    fooFROM barJOIN baz;
✓ Best practice
SELECT    fooFROM barCROSS JOIN baz;
AM09ambiguous.order_by_limit

Use of LIMIT and OFFSET without ORDER BY may lead to non-deterministic results.

✗ Anti-pattern
SELECT *FROM fooLIMIT 10 OFFSET 5;
✓ Best practice
SELECT *FROM fooORDER BY idLIMIT 10 OFFSET 5;

Capitalisation

Consistent casing of keywords, identifiers, functions, literals and types.

CP01capitalisation.keywordscorefixable

Inconsistent capitalisation of keywords.

✗ Anti-pattern
select    aFROM foo
✓ Best practice
SELECT    aFROM foo-- Also goodselect    afrom foo
capitalisation_policy = consistentignore_words = Noneignore_words_regex = None
  • Policies: consistent, upper, lower, capitalise.
  • Legacy code: L010
CP02capitalisation.identifierscorefixable

Inconsistent capitalisation of unquoted identifiers.

✗ Anti-pattern
select    a,    Bfrom foo
✓ Best practice
select    a,    bfrom foo;-- ...also good...select    A,    Bfrom foo;--- ...or for comparison with our more complex example, this too:select    col_1 + col_2 as col_3,    "COL_4" as col_5from foo as bar
extended_capitalisation_policy = consistentunquoted_identifiers_policy = allignore_words = Noneignore_words_regex = None
  • Extended policies add pascal, camel and snake.
  • Legacy code: L014
CP03capitalisation.functionscorefixable

Inconsistent capitalisation of function names.

✗ Anti-pattern
SELECT    sum(a) AS aa,    SUM(b) AS bbFROM foo
✓ Best practice
SELECT    sum(a) AS aa,    sum(b) AS bbFROM foo
extended_capitalisation_policy = consistentignore_words = Noneignore_words_regex = None
  • Off for ClickHouse (case-sensitive function names).
  • Legacy code: L030
CP04capitalisation.literalscorefixable

Inconsistent capitalisation of boolean/null literal.

✗ Anti-pattern
select    a,    null,    TRUE,    falsefrom foo
✓ Best practice
select    a,    NULL,    TRUE,    FALSEfrom foo-- Also goodselect    a,    null,    true,    falsefrom foo
capitalisation_policy = consistentignore_words = Noneignore_words_regex = None
  • Legacy code: L040
CP05capitalisation.typescorefixable

Inconsistent capitalisation of datatypes.

✗ Anti-pattern
CREATE TABLE t (    a int unsigned,    b VARCHAR(15));
✓ Best practice
CREATE TABLE t (    a INT UNSIGNED,    b VARCHAR(15));
extended_capitalisation_policy = consistentignore_words = Noneignore_words_regex = None
  • Legacy code: L063

Convention

Pick one way of writing equivalent SQL.

CV01convention.not_equalfixable

Consistent usage of '!=' or '<>' for "not equal to" operator.

✗ Anti-pattern
SELECT * FROM X WHERE 1 <> 2 AND 3 != 4;
✓ Best practice
SELECT * FROM X WHERE 1 != 2 AND 3 != 4;
preferred_not_equal_style = consistent
  • Legacy code: L061
CV02convention.coalescefixable

Use 'COALESCE' instead of 'IFNULL' or 'NVL'.

✗ Anti-pattern
SELECT ifnull(foo, 0) AS barFROM baz;SELECT nvl(foo, 0) AS barFROM baz;
✓ Best practice
SELECT coalesce(foo, 0) AS barFROM baz;
  • Legacy code: L060
CV03convention.select_trailing_commacorefixable

Trailing commas within select clause.

✗ Anti-pattern
SELECT    a,    b,FROM foo
✓ Best practice
SELECT    a,    bFROM foo
select_clause_trailing_comma = forbid
  • Or require, or require_multiline_forbid_single_line.
  • Legacy code: L038
CV04convention.count_rowscorefixable

Use consistent syntax to express "count number of rows".

✗ Anti-pattern
select    count(1)from table_a
✓ Best practice
select    count(*)from table_a
prefer_count_1 = Falseprefer_count_0 = False
  • Default prefers COUNT(*); prefer_count_1 wins if both are set.
  • Legacy code: L047
CV05convention.is_nullcorefixable

Comparisons with NULL should use "IS" or "IS NOT".

✗ Anti-pattern
SELECT    aFROM fooWHERE a = NULL
✓ Best practice
SELECT    aFROM fooWHERE a IS NULL
  • Legacy code: L049
CV06convention.terminatorfixable

Statements must end with a semi-colon.

✗ Anti-pattern
SELECT    aFROM foo;SELECT    bFROM bar••;
✓ Best practice
SELECT    aFROM foo;
multiline_newline = Falserequire_final_semicolon = False
  • Legacy code: L052
CV07convention.statement_bracketsfixable

Top-level statements should not be wrapped in brackets.

✗ Anti-pattern
(SELECT    fooFROM bar)-- This also applies to statements containing a sub-query.(SELECT    fooFROM (SELECT * FROM bar))
✓ Best practice
SELECT    fooFROM bar-- Likewise for statements containing a sub-query.SELECT    fooFROM (SELECT * FROM bar)
  • Legacy code: L053
CV08convention.left_join

Use 'LEFT JOIN' instead of 'RIGHT JOIN'.

✗ Anti-pattern
SELECT    foo.col1,    bar.col2FROM fooRIGHT JOIN bar    ON foo.bar_id = bar.id;
✓ Best practice
SELECT    foo.col1,    bar.col2FROM barLEFT JOIN foo    ON foo.bar_id = bar.id;
  • Legacy code: L055
CV09convention.blocked_wordsopt-in

Block a list of configurable words from being used.

✗ Anti-pattern
SELECT * FROM deprecated_table WHERE 1 = 1;CREATE TABLE myschema.t1 (a BOOL);
✓ Best practice
SELECT * FROM another_table WHERE 1 = 1;CREATE TABLE myschema.t1 (a BOOLEAN);
blocked_words = Noneblocked_regex = Nonematch_source = False
  • Does nothing until blocked_words or blocked_regex is set.
  • Legacy code: L062
CV10convention.quoted_literalsfixableopt-in

Consistent usage of preferred quotes for quoted literals.

✗ Anti-pattern
select    "abc",    'abc',    "\"",    "abc" = 'abc'from foo
✓ Best practice
select    "abc",    "abc",    '"',    "abc" = "abc"from foo
preferred_quoted_literal_style = consistentforce_enable = False
  • Only for dialects that allow both quote styles for literals (e.g. bigquery, databricks, hive, mysql, sparksql).
  • Legacy code: L064
CV11convention.casting_stylefixable

Enforce consistent type casting style.

✗ Anti-pattern
SELECT    CONVERT(int, 1) AS bar,    100::int::text,    CAST(10 AS text) AS cooFROM foo;
✓ Best practice
SELECT    CAST(1 AS int) AS bar,    CAST(CAST(100 AS int) AS text),    CAST(10 AS text) AS cooFROM foo;
preferred_type_casting_style = consistent
  • Styles: consistent, cast, convert, shorthand (::).
  • Legacy code: L067
CV12convention.join_conditionfixable

Use JOIN ... ON ... instead of WHERE ... for join conditions.

✗ Anti-pattern
SELECT    foo.a    , bar.bFROM fooJOIN barWHERE foo.x = bar.y;
✓ Best practice
SELECT    foo.a    , bar.bFROM fooJOIN barON foo.x = bar.y;
CV13convention.last_select_staropt-in

The final 'SELECT' of a CTE model should be 'SELECT * FROM ...'.

✗ Anti-pattern
WITH final AS (    SELECT        a,        b    FROM foo)SELECT    a,    bFROM final
✓ Best practice
WITH final AS (    SELECT        a,        b    FROM foo)SELECT * FROM final
force_enable = False
  • Off by default: enable with force_enable = True.

Jinja

Templated SQL.

JJ01jinja.paddingcorefixableopt-in

Jinja tags should have a single whitespace on either side.

✗ Anti-pattern
SELECT {{    a     }} from {{ref('foo')}}
✓ Best practice
SELECT {{ a }} from {{ ref('foo') }};SELECT {{ a }} from {{    ref('foo')}};
  • Only with the jinja (or dbt) templater.
  • Legacy code: L046

Layout

Whitespace, indentation, line breaks. Mostly auto-fixable.

LT01layout.spacingcorefixable

Inappropriate Spacing.

✗ Anti-pattern
SELECT    a,        b(c) as d••FROM foo••••JOIN bar USING(a)
✓ Best practice
SELECT    a, b(c) as dFROM fooJOIN bar USING (a)
  • Tune spacing in the [sqlfluff:layout:type:*] sections, not on the rule.
  • Legacy code: L001, L005, L006, L008, L023, L024, L039, L048, L071
LT02layout.indentcorefixable

Incorrect Indentation.

✗ Anti-pattern
SELECT••→a,•••••bFROM foo
✓ Best practice
SELECT••••a,••••bFROM foo
  • Tune with [sqlfluff:indentation]: indent_unit, tab_space_size, indented_joins…
  • Legacy code: L002, L003, L004
LT03layout.operatorsfixable

Operators should follow a standard for being before/after newlines.

✗ Anti-pattern
SELECT    a +    bFROM foo
✓ Best practice
SELECT    a    + bFROM foo
  • Position set by [sqlfluff:layout:type:binary_operator] line_position (leading).
  • Legacy code: L007
LT04layout.commasfixable

Leading/Trailing comma enforcement.

✗ Anti-pattern
SELECT    a    , b,    cFROM foo
✓ Best practice
SELECT    a,    b,    cFROM foo-- Alternatively, set the configuration file to 'leading'-- and then the following would be acceptable:SELECT    a    , b    , cFROM foo
  • Position set by [sqlfluff:layout:type:comma] line_position (trailing).
  • Legacy code: L019
LT05layout.long_linescorefixable

Line is too long.

✗ Anti-pattern
SELECT order_id, customer_id, order_date, ship_date, total_amount, currency FROM orders
✓ Best practice
SELECT    order_id,    customer_id,    order_date,    ship_date,    total_amount,    currencyFROM orders
ignore_comment_lines = Falseignore_comment_clauses = False
  • Limit is the core max_line_length (default 80).
  • Legacy code: L016
LT06layout.functionscorefixable

Function name not immediately followed by parenthesis.

✗ Anti-pattern
SELECT    sum (a)FROM foo
✓ Best practice
SELECT    sum(a)FROM foo
  • Legacy code: L017
LT07layout.cte_bracketcorefixable

'WITH' clause closing bracket should be on a new line.

✗ Anti-pattern
WITH zoo AS (    SELECT a FROM foo)SELECT * FROM zoo
✓ Best practice
WITH zoo AS (    SELECT a FROM foo)SELECT * FROM zoo
  • Legacy code: L018
LT08layout.cte_newlinecorefixable

Blank line expected but not found after CTE closing bracket.

✗ Anti-pattern
WITH plop AS (    SELECT * FROM foo)SELECT a FROM plop
✓ Best practice
WITH plop AS (    SELECT * FROM foo)SELECT a FROM plop
  • Legacy code: L022
LT09layout.select_targetsfixable

Select targets should be on a new line unless there is only one select target.

✗ Anti-pattern
select a, bfrom foo;-- Single select target on its own line-- (with default ``single_target_policy = same_line``).SELECT    aFROM foo;
✓ Best practice
select    a,    bfrom foo;-- Single select target on the same line as the ``SELECT``-- keyword (with default ``single_target_policy = same_line``).SELECT aFROM foo;-- With ``single_target_policy = new_line``, single select-- targets must also be on a new line for consistency.SELECT    aFROM foo;-- When select targets span multiple lines, however they-- can still be on a new line.SELECT    SUM(        1 + SUM(            2 + 3        )    ) AS colFROM test_table;
wildcard_policy = singlesingle_target_policy = same_line
  • wildcard_policy = multiple treats * as many targets; single_target_policy = new_line moves even one target down.
  • Legacy code: L036
LT10layout.select_modifierscorefixable

'SELECT' modifiers (e.g. 'DISTINCT') must be on the same line as 'SELECT'.

✗ Anti-pattern
select    distinct a,    bfrom x
✓ Best practice
select distinct    a,    bfrom x
  • Legacy code: L041
LT11layout.set_operatorscorefixable

Set operators should be surrounded by newlines.

✗ Anti-pattern
SELECT 'a' AS col UNION ALLSELECT 'b' AS col
✓ Best practice
SELECT 'a' AS colUNION ALLSELECT 'b' AS col
  • Legacy code: L065
LT12layout.end_of_filecorefixable

Files must end with a single trailing newline.

✗ Anti-pattern
SELECT    aFROM foo$-- Ending on an indented line means there is no newline-- at the end of the file, the • represents space.SELECT••••aFROM••••foo••••$-- Ending on a semi-colon means the last line is not a-- newline.SELECT    aFROM foo;$-- Ending with multiple newlines.SELECT    aFROM foo$
✓ Best practice
SELECT    aFROM foo$-- Ensuring the last line is not indented so is just a-- newline.SELECT••••aFROM••••foo$-- Even when ending on a semi-colon, ensure there is a-- newline after.SELECT    aFROM foo;$
  • Legacy code: L009
LT13layout.start_of_filefixable

Files must not begin with newlines or whitespace.

✗ Anti-pattern
^SELECT    aFROM foo-- Beginning on an indented line is also forbidden,-- (the • represents space).••••SELECT••••aFROM••••foo
✓ Best practice
^SELECT    aFROM foo-- Including an initial block comment.^/*This is a description of my SQL code.*/SELECT    aFROM    foo-- Including an initial inline comment.^--This is a description of my SQL code.SELECT    aFROM    foo
  • Legacy code: L050
LT14layout.keyword_newlinefixable

Keyword clauses should follow a standard for being before/after newlines.

✗ Anti-pattern
SELECT 'a' AS col FROM tab WHERE x = 4 ORDER BY y LIMIT 5
✓ Best practice
SELECT 'a' AS colFROM tabWHERE x = 4ORDER BY yLIMIT 5
LT15layout.newlinesfixable

Too many consecutive blank lines.

✗ Anti-pattern
SELECT 'a' AS colFROM tabWHERE x = 4ORDER BY yLIMIT 5;
✓ Best practice
SELECT 'a' AS colFROM tabWHERE x = 4ORDER BY yLIMIT 5;
maximum_empty_lines_between_statements = 2maximum_empty_lines_inside_statements = 1maximum_empty_lines_between_batches = 1minimum_empty_lines_between_statements = 0

References

How columns and objects are referenced and quoted.

RF01references.fromcore

References cannot reference objects not present in 'FROM' clause.

✗ Anti-pattern
SELECT    vee.aFROM foo
✓ Best practice
SELECT    aFROM foo
force_enable = False
  • Off for bigquery, soql and sparksql (structs); force_enable = True to turn on.
  • Legacy code: L026
RF02references.qualification

References should be qualified if select has more than one referenced table/view.

✗ Anti-pattern
SELECT a, bFROM fooLEFT JOIN vee ON vee.a = foo.a
✓ Best practice
SELECT foo.a, vee.bFROM fooLEFT JOIN vee ON vee.a = foo.a
ignore_words = Noneignore_words_regex = Nonesubqueries_ignore_external_references = False
  • Legacy code: L027
RF03references.consistentfixable

Column references should be qualified consistently in single table statements.

✗ Anti-pattern
SELECT    a,    foo.bFROM foo
✓ Best practice
SELECT    a,    bFROM foo-- Also goodSELECT    foo.a,    foo.bFROM foo
single_table_references = consistentforce_enable = False
  • Off for athena, bigquery, hive and redshift; force_enable = True to turn on.
  • Legacy code: L028
RF04references.keywords

Keywords should not be used as identifiers.

✗ Anti-pattern
SELECT    sum.aFROM foo AS sum
✓ Best practice
SELECT    vee.aFROM foo AS vee
unquoted_identifiers_policy = aliasesquoted_identifiers_policy = noneignore_words = Noneignore_words_regex = None
  • Legacy code: L029
RF05references.special_chars

Do not use special characters in identifiers.

✗ Anti-pattern
CREATE TABLE DBO.ColumnNames(    [Internal Space] INT,    [Greater>Than] INT,    [Less<Than] INT,    Number# INT)
✓ Best practice
CREATE TABLE DBO.ColumnNames(    [Internal_Space] INT,    [GreaterThan] INT,    [LessThan] INT,    NumberVal INT)
quoted_identifiers_policy = allunquoted_identifiers_policy = allallow_space_in_identifier = Falseadditional_allowed_characters = Noneignore_words = Noneignore_words_regex = None
  • Legacy code: L057
RF06references.quotingfixable

Unnecessary quoted identifier.

✗ Anti-pattern
SELECT "foo" as "bar";  -- For lowercase dialects like PostgresSELECT "FOO" as "BAR";  -- For uppercase dialects like Snowflake
✓ Best practice
SELECT foo as bar;  -- For lowercase dialects like PostgresSELECT FOO as BAR;  -- For uppercase dialects like Snowflake-- Note that where the case of the quoted identifier requires-- the quotes to remain, or where the identifier cannot be-- unquoted because it would be invalid to do so, the quotes-- may remain. For example:SELECT    "Case_Sensitive_Identifier" as is_allowed,    "Identifier with spaces or speci@l characters" as this_too,    "SELECT" as also_reserved_wordsFROM "My Table With Spaces"
prefer_quoted_identifiers = Falseprefer_quoted_keywords = Falseprefer_quoted_keyword_style = double_quotesignore_words = Noneignore_words_regex = Nonecase_sensitive = True
  • Legacy code: L059
RF07references.window_aliasopt-in

Do not reference a column alias inside its own 'OVER' clause.

✗ Anti-pattern
SELECT    t1.col1 AS id,    ROW_NUMBER() OVER (PARTITION BY id ORDER BY t1.ts) AS rnFROM t1LEFT JOIN t2 ON t1.col1 = t2.id
✓ Best practice
SELECT    t1.col1 AS id,    ROW_NUMBER() OVER (PARTITION BY t1.col1 ORDER BY t1.ts) AS rnFROM t1LEFT JOIN t2 ON t1.col1 = t2.id
force_enable = False
  • Off by default: enable with force_enable = True.

Structure

Query shape: CTEs, joins, CASE, redundancy.

ST01structure.else_nullfixable

Do not specify 'else null' in a case when statement (redundant).

✗ Anti-pattern
select    case        when name like '%cat%' then 'meow'        when name like '%dog%' then 'woof'        else null    endfrom x
✓ Best practice
select    case        when name like '%cat%' then 'meow'        when name like '%dog%' then 'woof'    endfrom x
  • Legacy code: L035
ST02structure.simple_casefixable

Unnecessary 'CASE' statement.

✗ Anti-pattern
select    case        when fab > 0 then true        else false    end as is_fabfrom fancy_table-- This rule can also simplify CASE statements-- that aim to fill NULL values.select    case        when fab is null then 0        else fab    end as fab_cleanfrom fancy_table-- This also covers where the case statement-- replaces NULL values with NULL values.select    case        when fab is null then null        else fab    end as fab_cleanfrom fancy_table
✓ Best practice
select    coalesce(fab > 0, false) as is_fabfrom fancy_table-- To fill NULL values.select    coalesce(fab, 0) as fab_cleanfrom fancy_table-- NULL filling NULL.select fab as fab_cleanfrom fancy_table
  • Legacy code: L043
ST03structure.unused_ctecore

Query defines a CTE (common-table expression) but does not use it.

✗ Anti-pattern
WITH cte1 AS (  SELECT a  FROM t),cte2 AS (  SELECT b  FROM u)SELECT *FROM cte1
✓ Best practice
WITH cte1 AS (  SELECT a  FROM t)SELECT *FROM cte1
  • Legacy code: L045
ST04structure.nested_casefixable

Nested 'CASE' statement in 'ELSE' clause could be flattened.

✗ Anti-pattern
SELECT  CASE    WHEN species = 'Cat' THEN 'Meow'    ELSE    CASE       WHEN species = 'Dog' THEN 'Woof'    END  END as soundFROM mytable
✓ Best practice
SELECT  CASE    WHEN species = 'Cat' THEN 'Meow'    WHEN species = 'Dog' THEN 'Woof'  END AS soundFROM mytable
  • Legacy code: L058
ST05structure.subqueryfixable

Join/From clauses should not contain subqueries. Use CTEs instead.

✗ Anti-pattern
select    a.x, a.y, b.zfrom ajoin (    select x, z from b) using(x)
✓ Best practice
with c as (    select x, z from b)select    a.x, a.y, c.zfrom ajoin c using(x)
forbid_subquery_in = join
  • forbid_subquery_in: join (default), from or both.
  • Legacy code: L042
ST06structure.column_orderfixable

Select wildcards then simple targets before calculations and aggregates.

✗ Anti-pattern
select    a,    *,    row_number() over (partition by id order by date) as y,    bfrom x
✓ Best practice
select    *,    a,    b,    row_number() over (partition by id order by date) as yfrom x
  • Legacy code: L034
ST07structure.usingfixable

Prefer specifying join keys instead of using 'USING'.

✗ Anti-pattern
SELECT    table_a.field_1,    table_b.field_2FROM    table_aINNER JOIN table_b USING (id)
✓ Best practice
SELECT    table_a.field_1,    table_b.field_2FROM    table_aINNER JOIN table_b    ON table_a.id = table_b.id
  • Off for ClickHouse. dbt dropped this from its style guide; many teams disable it.
  • Legacy code: L032
ST08structure.distinctcorefixable

'DISTINCT' used with parentheses.

✗ Anti-pattern
SELECT DISTINCT(a), b FROM foo
✓ Best practice
SELECT DISTINCT a, b FROM foo
  • Legacy code: L015
ST09structure.join_condition_orderfixable

Joins should list the table referenced earlier/later first.

✗ Anti-pattern
select    foo.a,    foo.b,    bar.cfrom fooleft join bar    -- This subcondition does not list    -- the table referenced earlier first:    on bar.a = foo.a    -- Neither does this subcondition:    and bar.b = foo.b
✓ Best practice
select    foo.a,    foo.b,    bar.cfrom fooleft join bar    on foo.a = bar.a    and foo.b = bar.b
preferred_first_table_in_join_clause = earlier
ST10structure.constant_expression

Redundant constant expression.

✗ Anti-pattern
SELECT *FROM my_table-- This following WHERE clause is redundant.WHERE my_table.col = my_table.col
✓ Best practice
SELECT *FROM my_table-- Replace with a condition that includes meaningful logic,-- or remove the condition entirely.WHERE my_table.col > 3
ST11structure.unused_join

Joined table not referenced in query.

✗ Anti-pattern
SELECT    foo.a,    foo.bFROM fooLEFT JOIN bar ON foo.a = bar.a
✓ Best practice
SELECT foo.a, vee.bFROM foo;SELECT    foo.a,    foo.b,    bar.cFROM fooLEFT JOIN bar ON foo.a = bar.a
  • Only checks OUTER joins (LEFT / RIGHT / FULL).
ST12structure.consecutive_semicolonsfixable

Consecutive semicolons detected.

✗ Anti-pattern
SELECT 1;;;;SELECT 2;
✓ Best practice
SELECT 1;SELECT 2;

Dialect-specific

Only run for one dialect: Oracle (OR), Postgres (PG), T-SQL (TQ).

OR01oracle.empty_batchfixableopt-in

Remove empty batches.

✗ Anti-pattern
SELECT 1 FROM DUAL;//
✓ Best practice
SELECT 1 FROM DUAL;/
  • Oracle dialect only.
PG01postgres.excessive_locksopt-in

Avoid excessive locks in PostgreSQL DDL statements.

✗ Anti-pattern
CREATE INDEX idx_foo ON bar (tenant_id);DROP INDEX idx_foo;REINDEX INDEX idx_foo;REFRESH MATERIALIZED VIEW my_view;
✓ Best practice
CREATE INDEX CONCURRENTLY idx_foo ON bar (tenant_id);DROP INDEX CONCURRENTLY idx_foo;REINDEX INDEX CONCURRENTLY idx_foo;REFRESH MATERIALIZED VIEW CONCURRENTLY my_view;
force_enable = False
  • Postgres only, off by default: force_enable = True.
PG02postgres.not_valid_foreign_keyopt-in

Create PostgreSQL foreign keys as 'NOT VALID' before validating.

✗ Anti-pattern
ALTER TABLE foo ADD CONSTRAINT fk_barFOREIGN KEY (bar_id) REFERENCES bar (id);
✓ Best practice
ALTER TABLE foo ADD CONSTRAINT fk_bar    FOREIGN KEY (bar_id) REFERENCES bar (id) NOT VALID;ALTER TABLE foo VALIDATE CONSTRAINT fk_bar;
force_enable = False
  • Postgres only, off by default: force_enable = True.
TQ01tsql.sp_prefixopt-in

'SP_' prefix should not be used for user-defined stored procedures in T-SQL.

✗ Anti-pattern
CREATE PROCEDURE dbo.sp_pull_dataASSELECT    ID,    DataDate,    CaseOutputFROM table1
✓ Best practice
CREATE PROCEDURE dbo.pull_dataASSELECT    ID,    DataDate,    CaseOutputFROM table1-- Alternatively prefix with USP_ to-- indicate a user-defined stored procedure.CREATE PROCEDURE dbo.usp_pull_dataASSELECT    ID,    DataDate,    CaseOutputFROM table1
  • T-SQL dialect only.
  • Legacy code: L056
TQ02tsql.procedure_begin_endfixableopt-in

Procedure bodies with multiple statements should be wrapped in BEGIN/END.

✗ Anti-pattern
CREATE PROCEDURE Reporting.MultipleStatementsASSELECT    [ID],    [DataDate],    [CaseOutput]FROM Table1;SELECT    [ID],    [DataDate],    [CaseOutput]FROM Table2;
✓ Best practice
CREATE PROCEDURE Reporting.MultipleStatementsASBEGIN    SELECT        [ID],        [DataDate],        [CaseOutput]    FROM Table1;    SELECT        [ID],        [DataDate],        [CaseOutput]    FROM Table2;END
  • T-SQL dialect only.
TQ03tsql.empty_batchfixableopt-in

Remove empty batches.

✗ Anti-pattern
CREATE TABLE dbo.test (    testcol1 INT NOT NULL,    testcol2 INT NOT NULL);GOGO
✓ Best practice
CREATE TABLE dbo.test (    testcol1 INT NOT NULL,    testcol2 INT NOT NULL);GO
  • T-SQL dialect only.
TQ04tsql.prefer_as_aliasfixableopt-in

Prefer ANSI-style 'AS' aliasing over 'alias = expression' in T-SQL.

✗ Anti-pattern
SELECThelp3 = 'hello',help4 = CASE WHEN help = 'apple' THEN 'hello' END
✓ Best practice
SELECT    'hello' AS help3,    CASE WHEN help = 'apple' THEN 'hello' END AS help4
force_enable = False
  • T-SQL only, off by default: force_enable = True.