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.
pip install sql-formatterVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to import the `format_sql` function and use it to format a multi-line SQL string.
Upgrade to version 0.6.2 or later, which includes specific fixes to address these parsing issues.
Ensure you are using version 0.6.1 or newer. If issues persist, consider using block comments (`/* ... */`) or utilizing the `/* sql-formatter-disable */` comments to explicitly exclude problematic sections from formatting.
For SQL containing templating, use the `paramTypes` configuration option to define custom regular expressions that treat these patterns as parameter placeholders during formatting. Example: `format(sql, paramTypes={'custom': [{'regex': r'\{\w+\}'}]})`.Refer to the latest documentation or use `sql-formatter --help` for the current CLI usage. The primary command is `sql-formatter <sql_file(s)>` with options like `--max-line-length`.
Use `import sql_formatter` or `from sql_formatter.core import format_sql`.
Ensure your virtual environment is activated, or verify that the directory containing Python scripts (e.g., `~/.local/bin` or a virtual environment's `bin`/`Scripts` folder) is in your system's PATH.
Correct the import statement to `from sql_formatter.core import format_sql`.
Change the argument `indent` to `indent_width`, for example: `format_sql(my_sql_string, indent_width=2)`.