SQL Formatting Best Practices
Consistent SQL style — keyword casing, indentation, aliasing, and CTE formatting for readability.
Published:
Tags: SQL formatting best practices, SQL style guide, consistent SQL code style
SQL Formatting Best Practices Consistent SQL style makes queries readable in pull requests, reviewable in code review, and debuggable under pressure. The SQL standard (ISO/IEC 9075) and popular style guides like GitLab's SQL Style Guide and dbt's SQL Style Guide provide widely-adopted conventions. These conventions represent the most widely adopted practices across data engineering teams. --- The Core Rules A minimal SQL style guide comes down to five decisions: Keyword casing — UPPERCASE or lowercase Indentation — 2 spaces or 4 spaces, tabs never Comma position — trailing (after each item) or leading (before each item) Alias style — keyword always, or optional Table qualification — full table names or short aliases Pick one option for each and enforce it with a formatter. Keyword Casing…
Frequently Asked Questions
What is a SQL style guide?
A SQL style guide defines consistent conventions for keyword casing, indentation, aliasing, join syntax, and comment format within a team or codebase. Examples include the Kickstarter SQL Style Guide and Simon Holywell's SQL Style Guide. Consistency matters more than which specific rules you choose.
Should SQL keywords be uppercase or lowercase?
Uppercase SQL keywords (SELECT, FROM, WHERE) are the historical convention and remain more common in production codebases. They visually separate keywords from identifiers. Lowercase is valid and preferred by some teams. The key is consistency across a project — use a formatter to enforce it.
How do I format CTEs in SQL?
Place each CTE on its own block with the AS keyword on the same line as the CTE name. Align the SELECT inside consistently indented. Separate multiple CTEs with a blank line for readability. Put the final query outside and below the WITH block.
How do I indent subqueries?
Indent the subquery contents by one level (2 or 4 spaces) relative to the enclosing query. Put the closing parenthesis on its own line, aligned with the opening. Name derived tables with a meaningful alias on the same line as the closing parenthesis.
What is SQLFluff?
SQLFluff is an open-source SQL linter and formatter that supports multiple dialects (ANSI, MySQL, PostgreSQL, MSSQL, BigQuery, Snowflake, and more). It applies configurable rules for indentation, casing, and style. Run it with `sqlfluff lint query.sql` or `sqlfluff fix query.sql`.
All articles · theproductguy.in