aliasing.tablefixableImplicit/explicit aliasing of table.
SELECT voo.aFROM foo vooSELECT voo.aFROM foo AS voo- Legacy code: L011
force_enable = True).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.
79 rules
layout, aliasing, structure…
Auto-fix
fix and format rewrite files
28 dialects
Postgres, BigQuery, Snowflake…
Templating
Jinja, dbt, placeholders
uv tool install sqlfluffprintf "[sqlfluff]\ndialect = postgres\n" > .sqlfluffsqlfluff lint .sqlfluff fix .pipx install)-1: all but one)== [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 = positionq_fixed.sql instead-- beforeselect a,b as c from foo fwhere a = null-- afterselect a, b as cfrom foowhere a is nullformat ignores --rules, but still respects --exclude-rules and config.
-c code only, -f yaml)[sqlfluff:layout:type:comma])[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 = upperConfig cascades: home dir → project root → each subfolder. Also read from setup.cfg, tox.ini and pyproject.toml ([tool.sqlfluff.core]).
all works too)templating) errorssqlfluff-templater-dbt):name, ?, $1… via param_style{table}[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 = devrepos: - repo: https://github.com/sqlfluff/sqlfluff rev: 4.5.0 hooks: - id: sqlfluff-lint - id: sqlfluff-fixansi athena bigqueryclickhouse databricks db2doris duckdb exasolflink greenplum hiveimpala mariadb materializemysql oracle postgresredshift snowflake soqlsparksql sqlite starrocksteradata trino tsqlverticaSelect rules by code (LT01), name (layout.spacing), group (core) or legacy code (L001).
How tables and columns are aliased.
aliasing.tablefixableSELECT voo.aFROM foo vooSELECT voo.aFROM foo AS vooaliasing.columncorefixableSELECT a alias_colFROM fooSELECT a AS alias_colFROM fooaliasing.expressioncoreAS clause.SELECT sum(a), sum(b)FROM fooSELECT sum(a) AS a_sum, sum(b) AS b_sumFROM fooallow_scalar = False to also flag a lone expression.aliasing.unique.tablecoreSELECT 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.fooSELECT 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 f2aliasing.unusedcorefixableSELECT aFROM foo AS zooSELECT zoo.aFROM foo AS zoo-- Alternatively...SELECT aFROM fooaliasing.lengthcoreopt-inSELECT SUM(o.amount) as order_amountFROM orders as oSELECT 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_idmin_alias_length or max_alias_length is set.aliasing.forbidfixableopt-inSELECT COUNT(o.customer_id) as order_amount, c.nameFROM orders as oJOIN customers as c on o.id = c.user_idSELECT 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_keyforce_enable = True.aliasing.unique.columncoreSELECT 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;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;aliasing.self_alias.columncorefixableSELECT col AS col, "Col" AS "Col", COL AS colFROM table;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;aliasing.requiredcoreSELECT *FROM ( SELECT 1 AS a)SELECT *FROM ( SELECT 1 AS a) AS derivedCode that works but hides intent.
ambiguous.distinctcoreSELECT DISTINCT aFROM fooGROUP BY aSELECT DISTINCT aFROM fooambiguous.unioncorefixableopt-inSELECT a, b FROM table_1UNIONSELECT a, b FROM table_2SELECT a, b FROM table_1UNION DISTINCTSELECT a, b FROM table_2UNION DISTINCT: ansi, bigquery, clickhouse, databricks, db2, hive, mysql, redshift, snowflake, trino.ambiguous.order_byfixableSELECT a, bFROM fooORDER BY a, b DESCSELECT a, bFROM fooORDER BY a ASC, b DESCambiguous.column_countWITH cte AS ( SELECT * FROM foo)SELECT * FROM cteUNIONSELECT a, b FROM tWITH cte AS ( SELECT * FROM foo)SELECT a, b FROM cteUNIONSELECT a, b FROM tambiguous.joinfixableSELECT fooFROM barJOIN baz;SELECT fooFROM barINNER JOIN baz;fully_qualify_join_types: inner (default), outer or both.ambiguous.column_referencescoreSELECT 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;-- 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;ambiguous.set_columnsWITH cte AS ( SELECT a, b FROM foo)SELECT * FROM cteUNIONSELECT c, d, e FROM tWITH cte AS ( SELECT a, b FROM foo)SELECT a, bFROM cteUNIONSELECT c, dFROM tambiguous.join_conditionfixableSELECT fooFROM barJOIN baz;SELECT fooFROM barCROSS JOIN baz;ambiguous.order_by_limitSELECT *FROM fooLIMIT 10 OFFSET 5;SELECT *FROM fooORDER BY idLIMIT 10 OFFSET 5;Consistent casing of keywords, identifiers, functions, literals and types.
capitalisation.keywordscorefixableselect aFROM fooSELECT aFROM foo-- Also goodselect afrom foocapitalisation.identifierscorefixableselect a, Bfrom fooselect 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 barcapitalisation.functionscorefixableSELECT sum(a) AS aa, SUM(b) AS bbFROM fooSELECT sum(a) AS aa, sum(b) AS bbFROM foocapitalisation.literalscorefixableselect a, null, TRUE, falsefrom fooselect a, NULL, TRUE, FALSEfrom foo-- Also goodselect a, null, true, falsefrom foocapitalisation.typescorefixableCREATE TABLE t ( a int unsigned, b VARCHAR(15));CREATE TABLE t ( a INT UNSIGNED, b VARCHAR(15));Pick one way of writing equivalent SQL.
convention.not_equalfixableSELECT * FROM X WHERE 1 <> 2 AND 3 != 4;SELECT * FROM X WHERE 1 != 2 AND 3 != 4;convention.coalescefixableSELECT ifnull(foo, 0) AS barFROM baz;SELECT nvl(foo, 0) AS barFROM baz;SELECT coalesce(foo, 0) AS barFROM baz;convention.select_trailing_commacorefixableSELECT a, b,FROM fooSELECT a, bFROM foorequire, or require_multiline_forbid_single_line.convention.count_rowscorefixableselect count(1)from table_aselect count(*)from table_aCOUNT(*); prefer_count_1 wins if both are set.convention.is_nullcorefixableSELECT aFROM fooWHERE a = NULLSELECT aFROM fooWHERE a IS NULLconvention.terminatorfixableSELECT aFROM foo;SELECT bFROM bar••;SELECT aFROM foo;convention.statement_bracketsfixable(SELECT fooFROM bar)-- This also applies to statements containing a sub-query.(SELECT fooFROM (SELECT * FROM bar))SELECT fooFROM bar-- Likewise for statements containing a sub-query.SELECT fooFROM (SELECT * FROM bar)convention.left_joinSELECT foo.col1, bar.col2FROM fooRIGHT JOIN bar ON foo.bar_id = bar.id;SELECT foo.col1, bar.col2FROM barLEFT JOIN foo ON foo.bar_id = bar.id;convention.blocked_wordsopt-inSELECT * FROM deprecated_table WHERE 1 = 1;CREATE TABLE myschema.t1 (a BOOL);SELECT * FROM another_table WHERE 1 = 1;CREATE TABLE myschema.t1 (a BOOLEAN);blocked_words or blocked_regex is set.convention.quoted_literalsfixableopt-inselect "abc", 'abc', "\"", "abc" = 'abc'from fooselect "abc", "abc", '"', "abc" = "abc"from fooconvention.casting_stylefixableSELECT CONVERT(int, 1) AS bar, 100::int::text, CAST(10 AS text) AS cooFROM foo;SELECT CAST(1 AS int) AS bar, CAST(CAST(100 AS int) AS text), CAST(10 AS text) AS cooFROM foo;::).convention.join_conditionfixableJOIN ... ON ... instead of WHERE ... for join conditions.SELECT foo.a , bar.bFROM fooJOIN barWHERE foo.x = bar.y;SELECT foo.a , bar.bFROM fooJOIN barON foo.x = bar.y;convention.last_select_staropt-inWITH final AS ( SELECT a, b FROM foo)SELECT a, bFROM finalWITH final AS ( SELECT a, b FROM foo)SELECT * FROM finalforce_enable = True.Templated SQL.
jinja.paddingcorefixableopt-inSELECT {{ a }} from {{ref('foo')}}SELECT {{ a }} from {{ ref('foo') }};SELECT {{ a }} from {{ ref('foo')}};Whitespace, indentation, line breaks. Mostly auto-fixable.
layout.spacingcorefixableSELECT a, b(c) as d••FROM foo••••JOIN bar USING(a)SELECT a, b(c) as dFROM fooJOIN bar USING (a)[sqlfluff:layout:type:*] sections, not on the rule.layout.indentcorefixableSELECT••→a,•••••bFROM fooSELECT••••a,••••bFROM foo[sqlfluff:indentation]: indent_unit, tab_space_size, indented_joins…layout.operatorsfixableSELECT a + bFROM fooSELECT a + bFROM foo[sqlfluff:layout:type:binary_operator] line_position (leading).layout.commasfixableSELECT a , b, cFROM fooSELECT a, b, cFROM foo-- Alternatively, set the configuration file to 'leading'-- and then the following would be acceptable:SELECT a , b , cFROM foo[sqlfluff:layout:type:comma] line_position (trailing).layout.long_linescorefixableSELECT order_id, customer_id, order_date, ship_date, total_amount, currency FROM ordersSELECT order_id, customer_id, order_date, ship_date, total_amount, currencyFROM ordersmax_line_length (default 80).layout.functionscorefixableSELECT sum (a)FROM fooSELECT sum(a)FROM foolayout.cte_bracketcorefixableWITH zoo AS ( SELECT a FROM foo)SELECT * FROM zooWITH zoo AS ( SELECT a FROM foo)SELECT * FROM zoolayout.cte_newlinecorefixableWITH plop AS ( SELECT * FROM foo)SELECT a FROM plopWITH plop AS ( SELECT * FROM foo)SELECT a FROM ploplayout.select_targetsfixableselect a, bfrom foo;-- Single select target on its own line-- (with default ``single_target_policy = same_line``).SELECT aFROM foo;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 = multiple treats * as many targets; single_target_policy = new_line moves even one target down.layout.select_modifierscorefixableselect distinct a, bfrom xselect distinct a, bfrom xlayout.set_operatorscorefixableSELECT 'a' AS col UNION ALLSELECT 'b' AS colSELECT 'a' AS colUNION ALLSELECT 'b' AS collayout.end_of_filecorefixableSELECT 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$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;$layout.start_of_filefixable^SELECT aFROM foo-- Beginning on an indented line is also forbidden,-- (the • represents space).••••SELECT••••aFROM••••foo^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 foolayout.keyword_newlinefixableSELECT 'a' AS col FROM tab WHERE x = 4 ORDER BY y LIMIT 5SELECT 'a' AS colFROM tabWHERE x = 4ORDER BY yLIMIT 5layout.newlinesfixableSELECT 'a' AS colFROM tabWHERE x = 4ORDER BY yLIMIT 5;SELECT 'a' AS colFROM tabWHERE x = 4ORDER BY yLIMIT 5;How columns and objects are referenced and quoted.
references.fromcoreSELECT vee.aFROM fooSELECT aFROM fooforce_enable = True to turn on.references.qualificationSELECT a, bFROM fooLEFT JOIN vee ON vee.a = foo.aSELECT foo.a, vee.bFROM fooLEFT JOIN vee ON vee.a = foo.areferences.consistentfixableSELECT a, foo.bFROM fooSELECT a, bFROM foo-- Also goodSELECT foo.a, foo.bFROM fooforce_enable = True to turn on.references.keywordsSELECT sum.aFROM foo AS sumSELECT vee.aFROM foo AS veereferences.special_charsCREATE TABLE DBO.ColumnNames( [Internal Space] INT, [Greater>Than] INT, [Less<Than] INT, Number# INT)CREATE TABLE DBO.ColumnNames( [Internal_Space] INT, [GreaterThan] INT, [LessThan] INT, NumberVal INT)references.quotingfixableSELECT "foo" as "bar"; -- For lowercase dialects like PostgresSELECT "FOO" as "BAR"; -- For uppercase dialects like SnowflakeSELECT 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"references.window_aliasopt-inSELECT t1.col1 AS id, ROW_NUMBER() OVER (PARTITION BY id ORDER BY t1.ts) AS rnFROM t1LEFT JOIN t2 ON t1.col1 = t2.idSELECT t1.col1 AS id, ROW_NUMBER() OVER (PARTITION BY t1.col1 ORDER BY t1.ts) AS rnFROM t1LEFT JOIN t2 ON t1.col1 = t2.idforce_enable = True.Query shape: CTEs, joins, CASE, redundancy.
structure.else_nullfixableselect case when name like '%cat%' then 'meow' when name like '%dog%' then 'woof' else null endfrom xselect case when name like '%cat%' then 'meow' when name like '%dog%' then 'woof' endfrom xstructure.simple_casefixableselect 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_tableselect 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_tablestructure.unused_ctecoreWITH cte1 AS ( SELECT a FROM t),cte2 AS ( SELECT b FROM u)SELECT *FROM cte1WITH cte1 AS ( SELECT a FROM t)SELECT *FROM cte1structure.nested_casefixableSELECT CASE WHEN species = 'Cat' THEN 'Meow' ELSE CASE WHEN species = 'Dog' THEN 'Woof' END END as soundFROM mytableSELECT CASE WHEN species = 'Cat' THEN 'Meow' WHEN species = 'Dog' THEN 'Woof' END AS soundFROM mytablestructure.subqueryfixableselect a.x, a.y, b.zfrom ajoin ( select x, z from b) using(x)with c as ( select x, z from b)select a.x, a.y, c.zfrom ajoin c using(x)forbid_subquery_in: join (default), from or both.structure.column_orderfixableselect a, *, row_number() over (partition by id order by date) as y, bfrom xselect *, a, b, row_number() over (partition by id order by date) as yfrom xstructure.usingfixableSELECT table_a.field_1, table_b.field_2FROM table_aINNER JOIN table_b USING (id)SELECT table_a.field_1, table_b.field_2FROM table_aINNER JOIN table_b ON table_a.id = table_b.idstructure.distinctcorefixableSELECT DISTINCT(a), b FROM fooSELECT DISTINCT a, b FROM foostructure.join_condition_orderfixableselect 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.bselect foo.a, foo.b, bar.cfrom fooleft join bar on foo.a = bar.a and foo.b = bar.bstructure.constant_expressionSELECT *FROM my_table-- This following WHERE clause is redundant.WHERE my_table.col = my_table.colSELECT *FROM my_table-- Replace with a condition that includes meaningful logic,-- or remove the condition entirely.WHERE my_table.col > 3structure.unused_joinSELECT foo.a, foo.bFROM fooLEFT JOIN bar ON foo.a = bar.aSELECT foo.a, vee.bFROM foo;SELECT foo.a, foo.b, bar.cFROM fooLEFT JOIN bar ON foo.a = bar.astructure.consecutive_semicolonsfixableSELECT 1;;;;SELECT 2;SELECT 1;SELECT 2;Only run for one dialect: Oracle (OR), Postgres (PG), T-SQL (TQ).
oracle.empty_batchfixableopt-inSELECT 1 FROM DUAL;//SELECT 1 FROM DUAL;/postgres.excessive_locksopt-inCREATE INDEX idx_foo ON bar (tenant_id);DROP INDEX idx_foo;REINDEX INDEX idx_foo;REFRESH MATERIALIZED VIEW my_view;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 = True.postgres.not_valid_foreign_keyopt-inALTER TABLE foo ADD CONSTRAINT fk_barFOREIGN KEY (bar_id) REFERENCES bar (id);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 = True.tsql.sp_prefixopt-inCREATE PROCEDURE dbo.sp_pull_dataASSELECT ID, DataDate, CaseOutputFROM table1CREATE 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 table1tsql.procedure_begin_endfixableopt-inCREATE PROCEDURE Reporting.MultipleStatementsASSELECT [ID], [DataDate], [CaseOutput]FROM Table1;SELECT [ID], [DataDate], [CaseOutput]FROM Table2;CREATE PROCEDURE Reporting.MultipleStatementsASBEGIN SELECT [ID], [DataDate], [CaseOutput] FROM Table1; SELECT [ID], [DataDate], [CaseOutput] FROM Table2;ENDtsql.empty_batchfixableopt-inCREATE TABLE dbo.test ( testcol1 INT NOT NULL, testcol2 INT NOT NULL);GOGOCREATE TABLE dbo.test ( testcol1 INT NOT NULL, testcol2 INT NOT NULL);GOtsql.prefer_as_aliasfixableopt-inSELECThelp3 = 'hello',help4 = CASE WHEN help = 'apple' THEN 'hello' ENDSELECT 'hello' AS help3, CASE WHEN help = 'apple' THEN 'hello' END AS help4force_enable = True.