SQL Formatter
sql-formatter is a Python library designed to format SQL queries, enhancing readability and quick understanding through consistent indentation and casing. It aims to standardize SQL query writing, similar to how 'black' formats Python code. The library provides both a command-line interface and a Python API, and is actively maintained with frequent bug fixes and feature enhancements.
Warnings
- gotcha SQL keywords embedded within table or variable names (e.g., 'select', 'and') could lead to incorrect formatting due to misinterpretation. [cite: Bugfixes in 0.6.2 release notes]
- gotcha Line comments starting with `--` might prematurely terminate formatting for subsequent SQL statements on the same line or block. [cite: Bugfixes in 0.6.1 release notes]
- gotcha The library does not inherently understand or format templating syntax (e.g., `SELECT {col} FROM {tablename}`). Such constructs might break formatting or be ignored.
- deprecated Several older command-line interface (CLI) commands were deprecated and subsequently removed, potentially causing 'command not found' errors if older scripts are used. [cite: Maintenance in 0.5.4 release notes]
Install
-
pip install sql-formatter
Imports
- format_sql
from sql_formatter.core import format_sql
Quickstart
from sql_formatter.core import format_sql example_sql = """ create or replace table mytable as -- mytable example seLecT a.asdf, b.qwer, -- some comment here c.asdf, -- some comment there b.asdf2 frOm table1 as a leFt join table2 as b -- and here a comment on a.asdf = b.asdf -- join this way """ formatted_sql = format_sql(example_sql) print(formatted_sql)