BytePane

SQL Formatter Online: Format & Beautify SQL Queries Free

SQL14 min read

Key Takeaways

  • SQL is used by 59% of all developers and 54.1% of professional developers, per the 2024 Stack Overflow Developer Survey (90,000+ respondents) — only JavaScript is more common.
  • No universal SQL formatting standard exists. The three main style guides (Holywell, Mazur, dbt) disagree on the most fundamental question: uppercase vs lowercase keywords.
  • SQLFluff is the de facto standard for teams: it combines formatting with linting, supports 15+ dialects (Postgres, MySQL, BigQuery, Snowflake, DuckDB), and integrates with CI/CD pipelines.
  • SQL formatting has zero effect on query performance — the database strips all whitespace before query compilation. It is entirely a developer productivity concern.
  • For a quick one-off format, use BytePane's SQL Formatter — it runs in-browser and supports multiple dialects with no setup.

Here is the misconception I see most often in code reviews: "SQL formatting doesn't matter that much — the database doesn't care about whitespace."

The first half is technically true. The database parser strips all whitespace before compilation. A query written as a single line and the same query formatted across 40 lines produce identical execution plans. The second half — that it therefore does not matter — is the wrong conclusion.

SQL formatting matters because humans read SQL, not just databases. The 2024 Stack Overflow Developer Survey found SQL is used by 54.1% of professional developers — second only to JavaScript at 64.6%. That means SQL code is reviewed, debugged, modified, and maintained by a massive developer population. Inconsistent formatting slows every one of those operations.

This guide covers: the three major SQL style guides and where they disagree, a tool comparison from one-off formatters to CI/CD-integrated linters, and how to set up automated SQL formatting in your project.

The Problem: Unformatted SQL Is Unreadable SQL

Start with the before/after. This is the same query — one written by someone in a hurry, one formatted:

-- Before: What does this even do?
select u.id,u.name,u.email,count(o.id) as order_count,sum(o.total) as lifetime_value from users u left join orders o on u.id=o.user_id where u.created_at > '2024-01-01' and u.status='active' group by u.id,u.name,u.email having count(o.id)>0 order by lifetime_value desc limit 100;
-- After: Formatted (dbt-style lowercase)
select
    u.id,
    u.name,
    u.email,
    count(o.id)  as order_count,
    sum(o.total) as lifetime_value

from users as u

left join orders as o
    on u.id = o.user_id

where
    u.created_at > '2024-01-01'
    and u.status = 'active'

group by
    u.id,
    u.name,
    u.email

having count(o.id) > 0

order by lifetime_value desc

limit 100

The formatted version takes 26 lines instead of 1, but a reviewer can now immediately see the join condition, the WHERE filters, the grouping keys, and the HAVING clause. Adding a column, modifying a filter, or catching a bug is dramatically faster. Paste either version into BytePane's SQL Formatter and it produces the formatted version in milliseconds.

The Three Major SQL Style Guides (And Where They Disagree)

Unlike JavaScript (Prettier), Python (Black), or Go (gofmt), SQL has no universally adopted formatter. Three style guides are widely referenced, and they disagree on the most fundamental question: should keywords be uppercase or lowercase?

1. Simon Holywell's SQL Style Guide (sqlstyle.guide)

The most cited SQL style guide, licensed under Creative Commons Attribution-ShareAlike 4.0. Holywell's guide is the established DBA and SQL Server convention:

  • UPPERCASE reserved keywords: SELECT, WHERE, FROM, JOIN, GROUP BY
  • snake_case for identifiers: first_name, not firstName
  • Maximum 30 characters for identifiers
  • Singular table names (staff, not employees)
  • Right-align keywords to create a visual "river" on the left side
  • ISO 8601 dates: YYYY-MM-DDTHH:MM:SS
  • Prefer BETWEEN over chained AND conditions
-- Holywell style: keywords uppercase, right-aligned "river"
SELECT a.title,
       a.release_date,
       a.recording_date
  FROM album AS a
 WHERE a.title = 'Charcoal Lane'
    OR a.title = 'The New Danger';

2. Matt Mazur's SQL Style Guide

An opinionated guide by data analyst Matt Mazur, popular in startup and analytics communities:

  • lowercase keywords — the opposite of Holywell
  • Each column on its own line
  • Plural snake_case table names (users, not user)
  • Boolean columns prefixed: is_, has_, does_
  • Datetime columns suffixed: created_at; date-only: birth_date
  • Use != not <>
  • Always write inner join explicitly (never just join)

3. dbt's Official SQL Style Guide

dbt (data build tool) has become the dominant SQL transformation framework in modern data stacks, with hundreds of thousands of practitioners. Its official style guide is the most influential in analytics engineering:

  • Lowercase keywords — rationale: "modern syntax highlighting makes uppercase unnecessary, and uppercase is harder to type"
  • Trailing commas (comma at end of line, not beginning)
  • Explicit join types always
  • CTEs over subqueries for readability
  • SQLFluff as the enforcement tool with a published .sqlfluff config

The dbt ecosystem's influence on modern data engineering is shifting the balance toward lowercase. If you are building analytics SQL (dbt models, Snowflake, BigQuery, Databricks), lowercase is increasingly the default. If you are in a traditional SQL Server or Oracle environment, UPPERCASE is the established norm.

ConventionHolywellMazurdbt
Keyword caseUPPERCASElowercaselowercase
Table namessingular (staff)plural (users)plural (users)
Comma placementtrailingtrailingtrailing
Alignmentkeyword "river"4-space indent4-space indent
NOT EQUAL<>!=!=
EcosystemDBAs, SQL ServerStartups, analyticsData engineering

The only universally wrong answer is mixing them. Inconsistency within a codebase is worse than any specific convention choice.

SQL Formatting Tools Comparison

The tool landscape spans from lightweight online formatters to full linter-formatters with CI/CD integration. The right choice depends on your workflow.

SQLFluff: The Production Standard

SQLFluff is an open-source SQL linter and formatter (Python), maintained on GitHub with active development through 2025. It is the official recommendation of dbt and supports 15+ dialects:

# Install
pip install sqlfluff

# Lint a file (shows style violations)
sqlfluff lint --dialect postgres my_query.sql

# Auto-fix formatting issues
sqlfluff fix --dialect postgres my_query.sql

# Lint an entire dbt project
sqlfluff lint --dialect bigquery models/

# Example .sqlfluff config
[sqlfluff]
dialect = postgres
templater = dbt
max_line_length = 120

[sqlfluff:rules:capitalisation.keywords]
capitalisation_policy = lower   # lowercase keywords (dbt style)

[sqlfluff:rules:aliasing.table]
aliasing = explicit             # always require AS keyword

SQLFluff catches more than formatting issues. Rules like ambiguous.column_references flag queries where column names are ambiguous across multiple joined tables — the kind of bug that causes silent data errors in production.

pgFormatter: Best for PostgreSQL

pgFormatter by Gilles Darold produces notably clean output for PostgreSQL-specific syntax including JSONB operators, CTEs, window functions, and Postgres extensions. It is Perl-based with a CGI web interface and a command-line binary. Output quality for complex Postgres queries is visibly better than generic formatters.

# Install via package manager
brew install pgformatter          # macOS
sudo apt install pgformatter      # Ubuntu

# Format a file
pg_format -i my_query.sql        # in-place

# Format with specific indent
pg_format --indent 4 my_query.sql

# Format from stdin
cat complex_query.sql | pg_format

sql-formatter (npm): For JavaScript Projects

The sql-formatter package (github.com/sql-formatter-org/sql-formatter) is the standard choice for Node.js projects and web tooling. It is what powers most browser-based SQL formatters including BytePane's SQL Formatter tool.

npm install sql-formatter

import { format } from 'sql-formatter';

const ugly = "select u.id,u.name from users u where u.active=true";

const pretty = format(ugly, {
  language: 'postgresql',   // 'mysql' | 'tsql' | 'bigquery' | 'spark' etc.
  tabWidth: 2,
  keywordCase: 'lower',     // 'upper' | 'lower' | 'preserve'
  linesBetweenQueries: 2,
  indentStyle: 'standard',  // 'standard' | 'tabularLeft' | 'tabularRight'
});

// Output:
// select
//   u.id,
//   u.name
// from
//   users u
// where
//   u.active = true

Tool Comparison Matrix

ToolLintingCI/CDDialectsBest For
BytePane SQL FormatterFormat onlyNo8+Quick one-off formatting
SQLFluffYes (deep)Yes15+Teams, dbt projects, enforcement
pgFormatterFormat onlyVia scriptPostgreSQL onlyBest Postgres output quality
sql-formatter (npm)Format onlyVia script12+JS/Node.js projects, web tools
sqlfmtOpinionated formatYesdbt SQLdbt-first teams wanting auto-format
DBeaver built-inFormat onlyNoAll (auto-detect)GUI database work

How to Format SQL in Your IDE

VS Code

Install the SQL Formatter extension by sql-formatter-org (the official extension, distinct from the deprecated "prettier-plugin-sql-vscode"). Open any .sql file and press Shift+Alt+F (Windows/Linux) or Shift+Option+F (Mac) to format.

// settings.json — configure dialect and keyword case
{
  "[sql]": {
    "editor.defaultFormatter": "inferrinizzard.prettier-sql-vscode",
    "editor.formatOnSave": true
  },
  "sql-formatter.dialect": "postgresql",
  "sql-formatter.keywordCase": "lower",
  "sql-formatter.tabWidth": 4
}

DBeaver

In the SQL Editor, press Ctrl+Shift+F (Windows/Linux) or Cmd+Shift+F (Mac). DBeaver auto-detects the connected database type and applies dialect-appropriate formatting. Configure keyword case at Window → Preferences → Editors → SQL Editor → Formatting.

Command Line (any SQL file)

# Using sqlfluff (recommended for teams)
sqlfluff fix --dialect postgres queries/

# Using sql-formatter CLI (npm)
npx sql-formatter --language postgresql --tab-width 2 < ugly.sql > pretty.sql

# Using pgFormatter (Postgres only)
pg_format -i queries/*.sql

CI/CD Integration: Enforcing SQL Style Automatically

Manual formatting reviews in code review are expensive and inconsistent. The right approach is to block unformatted SQL at the pre-commit or CI stage, the same way you would block JavaScript without Prettier.

pre-commit Hook (SQLFluff)

# .pre-commit-config.yaml
repos:
  - repo: https://github.com/sqlfluff/sqlfluff
    rev: 3.0.7
    hooks:
      - id: sqlfluff-lint       # blocks commit if violations found
        args: [--dialect, postgres]
      - id: sqlfluff-fix        # auto-fixes what it can before commit
        args: [--dialect, postgres]

GitHub Actions

# .github/workflows/sql-lint.yml
name: SQL Style Check
on: [pull_request]

jobs:
  sqlfluff:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: '3.11'
      - run: pip install sqlfluff sqlfluff-templater-dbt
      - name: Lint SQL
        run: sqlfluff lint --dialect bigquery models/

With this setup, PRs that add unformatted SQL fail the CI check automatically. No reviewer needs to leave "please format this" comments. The same principle applies to JSON formatting in your API layer — automated enforcement is faster and more consistent than manual review.

SQL Formatting for Specific Dialects

Dialect matters. Formatting rules that work for standard ANSI SQL can break or produce incorrect output for dialect-specific syntax.

PostgreSQL

PostgreSQL-specific syntax that formatters need to handle: JSONB operators (->>, @>), array operations, FILTER (WHERE ...) in aggregates, LATERAL joins, and dollar-quoting in function bodies. pgFormatter handles all of these; generic formatters frequently mangle them.

BigQuery

BigQuery uses backtick-quoted identifiers (`project.dataset.table`), ARRAY and STRUCT types, and pipe syntax in newer GoogleSQL. Use SQLFluff with --dialect bigquery or sql-formatter with language: 'bigquery'.

T-SQL (SQL Server)

T-SQL uses square bracket identifiers ([TableName]), TOP N instead of LIMIT N, and NOLOCK table hints. SQLFluff's tsql dialect handles all of this correctly. For T-SQL style, John McCall's T-SQL Style Guide (lowlydba.github.io/tsqlstyle.guide) is a community-maintained variant of Holywell's guide adapted for SQL Server conventions.

Frequently Asked Questions

Should SQL keywords be uppercase or lowercase?
No universal standard exists. Holywell's SQL Style Guide prescribes UPPERCASE (dominant in DBA and SQL Server environments). dbt's official guide and Matt Mazur's guide recommend lowercase, arguing modern editors make uppercase unnecessary. The dbt ecosystem is shifting data engineering toward lowercase. Pick one, enforce it with SQLFluff, and never mix them in the same codebase.
What is the best SQL formatter for PostgreSQL?
pgFormatter produces the highest-quality output for PostgreSQL-specific syntax (JSONB operators, window functions, CTEs). For CI/CD enforcement across a project, SQLFluff with --dialect postgres is better because it combines formatting with semantic linting and integrates with pre-commit hooks and GitHub Actions.
How do I format SQL in VS Code?
Install the "SQL Formatter" extension by sql-formatter-org. Open a .sql file and press Shift+Alt+F (Windows/Linux) or Shift+Option+F (Mac). Configure dialect and keyword case in settings.json under the [sql] language block. For SQL in JS template literals, use prettier-plugin-sql.
What is SQLFluff and how does it differ from a formatter?
SQLFluff is both a linter and formatter. Pure formatters only rearrange whitespace. SQLFluff also detects semantic issues: ambiguous column references, implicit type conversions, deprecated syntax. It supports 15+ dialects and is the official dbt recommendation. Think of it as ESLint for SQL.
How do I auto-format SQL in a CI/CD pipeline?
Add SQLFluff to .pre-commit-config.yaml with the sqlfluff-lint and sqlfluff-fix hooks. In GitHub Actions, run "sqlfluff lint --dialect postgres ." as a PR check step. This enforces consistent formatting on every PR without manual reviewer comments.
Does SQL formatting affect query performance?
No. The database parser strips all whitespace before building the execution plan. Identical queries formatted differently produce identical bytecodes. Formatting is purely a developer productivity concern — it affects read speed, review speed, and debugging speed, not database execution time.
What SQL dialects does the BytePane SQL Formatter support?
BytePane's SQL Formatter supports MySQL, PostgreSQL, T-SQL (SQL Server), Oracle, SQLite, BigQuery, Snowflake, and standard ANSI SQL. Select your dialect from the dropdown for dialect-specific keyword handling and formatting rules.

Format Your SQL Instantly

Paste any SQL query into BytePane's free SQL Formatter. Supports MySQL, PostgreSQL, T-SQL, BigQuery, Snowflake, and more. Choose keyword case (uppercase or lowercase), set your dialect, and get clean output in milliseconds — no signup, no server uploads.

Open SQL Formatter

Related Articles