BytePane

SQL Formatter Online: Format SQL Query Free

Paste a messy SQL query and format it into readable, reviewable SQL before you ship it.

Open SQL Formatter
SQLUpdated September 17, 202614 min read

Format SQL now

Paste SQL, get clean output

Use the free browser-based SQL Formatter for standard SQL used across MySQL, PostgreSQL, SQL Server, SQLite, and Oracle. It is the fastest route if you came here to clean a query, not read a full style guide; it does not apply dialect-specific rules.

Key Takeaways

  • ▸SQL is used by 51% of all respondents and 54.1% of professional developers in the 2024 Stack Overflow Developer Survey; among professional developers only JavaScript (64.6%) 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 a widely used choice for teams: it combines formatting fixes with linting, supports many dialects (Postgres, MySQL, BigQuery, Snowflake, DuckDB and more), is recommended by dbt's style guide, and integrates with CI/CD pipelines.
  • ▸SQL formatting does not change the execution plan, whitespace is not significant to the optimizer. The main caveat is plan caches that match query text exactly (for example SQL Server ad hoc plans).
  • ▸For a quick one-off format, use BytePane's SQL Formatter, it runs in-browser with no setup and handles standard SQL keywords.

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 mostly true. Whitespace is not significant to the SQL parser, so a query written as a single line and the same query formatted across 40 lines get the same execution plan (plan caches that match exact query text are the exception). 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% in that group. 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 the one-line version into BytePane's SQL Formatter for a similar clause-per-line layout (it uppercases keywords rather than using the lowercase dbt style shown here).

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)

A widely cited SQL style guide, licensed under Creative Commons Attribution-ShareAlike 4.0, closer to traditional DBA conventions:

  • UPPERCASE reserved keywords: SELECT, WHERE, FROM, JOIN, GROUP BY
  • snake_case for identifiers: first_name, not firstName
  • Maximum 30 bytes (in practice 30 characters) for identifiers
  • Collective table names, or less ideally plural (staff preferred over employees)
  • Right-align keywords to create a visual "river" on the left side
  • ISO 8601 dates: YYYY-MM-DDTHH:MM:SS
  • Use BETWEEN where possible instead of combining conditions with AND
-- 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 <>
  • Include inner for inner joins (inner join, not just join)

3. dbt's Official SQL Style Guide

dbt (data build tool) is a widely used SQL transformation framework in modern data stacks, and its published style guide is influential in analytics engineering:

  • Lowercase keywords, "Field names, keywords, and function names should all be lowercase"
  • Trailing commas (comma at end of line, not beginning)
  • Four-space indents
  • Explicit join types (inner join instead of join)
  • CTEs at the top of the model for references and logic
  • SQLFluff as the enforcement tool, with an example .sqlfluff config

In practice, lowercase is common in dbt-style analytics SQL (dbt models, Snowflake, BigQuery, Databricks), while UPPERCASE keywords remain common in traditional SQL Server and Oracle codebases. Follow whatever your team already uses.

ConventionHolywellMazurdbt
Keyword caseUPPERCASElowercaselowercase
Table namescollective (staff), else pluralplural (users)plural (users)
Comma placementtrailingtrailingtrailing
Alignmentkeyword "river"left-aligned keywords4-space indent
NOT EQUALnot specified!=not specified
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 written in Python and maintained on GitHub. dbt's SQL style guide recommends it, and it supports many SQL 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

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

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

SQLFluff catches more than formatting issues. Rules like references.qualification require column references to be qualified when a query selects from more than one table, which makes it harder to read a column from the wrong joined table.

pgFormatter: Best for PostgreSQL

pgFormatter by Gilles Darold is a PostgreSQL-focused formatter designed around Postgres syntax such as JSONB operators, CTEs, and window functions. It is a Perl script that runs as a command-line tool (pg_format) or as a CGI web interface.

# 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 a specific indent (spaces, default 4)
pg_format -s 2 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 a common choice for Node.js projects and web tooling, and it is the library behind the SQL Formatter VSCode extension. (BytePane's SQL Formatter tool uses its own lightweight keyword-based formatter, not this library.)

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,
});

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

Tool Comparison Matrix

ToolLintingCI/CDDialectsBest For
BytePane SQL FormatterFormat onlyNoGeneric SQL (no dialect selector)Quick one-off formatting
SQLFluffYes (deep)YesMany (Postgres, BigQuery, T-SQL, more)Teams, dbt projects, enforcement
pgFormatterFormat onlyVia scriptPostgreSQL onlyPostgreSQL-focused formatting
sql-formatter (npm)Format onlyVia script15+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 VSCode extension (ReneSaarsoo.sql-formatter-vsc), built on the sql-formatter library and the successor to the no-longer-maintained Prettier SQL VSCode extension. Open any .sql file and run Format Document: Shift+Alt+F (Windows), Shift+Option+F (macOS), or Ctrl+Shift+I (Linux).

// settings.json, configure dialect and keyword case
{
  "[sql]": {
    "editor.defaultFormatter": "ReneSaarsoo.sql-formatter-vsc",
    "editor.formatOnSave": true,
    "editor.tabSize": 4
  },
  "SQL-Formatter-VSCode.dialect": "postgresql",
  "SQL-Formatter-VSCode.keywordCase": "lower"
}

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 ugly.sql --output 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

How do I format a SQL query online?▾
Paste the SQL query into BytePane's SQL Formatter and it reformats it in your browser without uploading the query to a server. It uppercases common SQL keywords, starts major clauses (SELECT, FROM, JOIN, WHERE, GROUP BY, ORDER BY, LIMIT) on new lines, puts each selected column on its own line, and indents AND/OR conditions. It is a general-purpose formatter with no dialect selector, so check dialect-specific syntax afterwards.
Should SQL keywords be uppercase or lowercase?▾
No universal standard exists. Simon Holywell's SQL Style Guide (sqlstyle.guide) says to always use uppercase for reserved keywords. dbt's SQL style guide and Matt Mazur's guide use lowercase; Mazur argues lowercase is just as readable and avoids holding down the Shift key. Pick one, enforce it with a tool such as SQLFluff, and do not mix them in the same codebase.
What is the best SQL formatter for PostgreSQL?▾
pgFormatter (github.com/darold/pgFormatter) is a formatter built specifically for PostgreSQL syntax such as JSONB operators, CTEs, and window functions. For project-wide enforcement in CI/CD, SQLFluff with the postgres dialect is usually a better fit because it combines linting with fixing and integrates with pre-commit hooks and GitHub Actions.
How do I format SQL in VS Code?▾
Install the "SQL Formatter VSCode" extension (ReneSaarsoo.sql-formatter-vsc), which is built on the sql-formatter library. Open a .sql file and run Format Document: Shift+Alt+F on Windows, Shift+Option+F on macOS, or Ctrl+Shift+I on Linux. Set the dialect and keyword case in settings.json with "SQL-Formatter-VSCode.dialect" and "SQL-Formatter-VSCode.keywordCase".
What is SQLFluff and how does it differ from a formatter?▾
SQLFluff is both a linter and a fixer. A pure formatter only rearranges whitespace and keyword case. SQLFluff also applies rules such as requiring qualified column references when a query selects from more than one table (references.qualification) and flagging inconsistent column references in GROUP BY/ORDER BY (ambiguous.column_references). It supports many SQL dialects (Postgres, MySQL, BigQuery, Snowflake, Spark, DuckDB and more), and dbt's SQL style guide recommends it for enforcing style rules.
How do I auto-format SQL in a CI/CD pipeline?▾
Use SQLFluff with a pre-commit hook. Add sqlfluff to .pre-commit-config.yaml with the "sqlfluff-lint" hook (fails the commit on violations) and the "sqlfluff-fix" hook (auto-fixes what it can). In GitHub Actions, run "sqlfluff lint --dialect postgres ." as a step in your PR workflow so unformatted SQL fails the check without manual review comments.
Does SQL formatting affect query performance?▾
Not the execution plan: whitespace and line breaks do not change how the optimizer plans a query. One caveat is plan caching. SQL Server, for example, matches ad hoc statements to cached plans character per character, so the same query sent with different whitespace can compile a separate cached plan. Formatting stored queries consistently, or using parameterized queries, avoids that.
What SQL dialects does the BytePane SQL Formatter support?▾
BytePane's SQL Formatter is a general-purpose formatter for standard SQL keywords shared by MySQL, PostgreSQL, SQLite, SQL Server, and Oracle. It has no dialect dropdown and does not apply dialect-specific rules; it preserves quoted strings, backtick identifiers, and [bracketed] identifiers. For dialect-aware formatting use sql-formatter, SQLFluff, or pgFormatter.

Format Your SQL Instantly

Paste any SQL query into BytePane's free SQL Formatter. It formats standard SQL used across MySQL, PostgreSQL, SQL Server, SQLite, and Oracle, uppercases keywords, and puts each clause on its own line, no signup, no server uploads.

Open SQL Formatter

Related Articles