How to pretty format the printing of SQL Queries in SQLAlchemy?

The project sqlparse is mature (10+ years) and still very active. sqlparse aims parsing, splitting and formatting SQL statements.

The following example uses sqlparse to pretty formats SQL files:

import argparse
import sqlparse

# Parse command line arguments
parser = argparse.ArgumentParser(prog="pretty_print_sql")
parser.add_argument("file", type=argparse.FileType("r"), nargs="+")
args = parser.parse_args()

# Pretty print input files
for file in args.file:
    print(sqlparse.format(file.read(), reindent=True, keyword_case='upper'))

To install sqlparse using pip for personal usage:

python3 -m pip install sqlparse --user --upgrade

To install sqlparse using pipenv (within a project):

python3 -m pipenv install sqlparse

You can use sqlparse package and sqlparse.format(sql, reindent=True, keyword_case='upper') should do what you want?


There's a couple of options to try:

  • Pygments
  • sqlparse
  • format-sql