SQL_Parse
A small Python tool that automatically indents one-line or messy SQL queries to make them readable.
SQL_Parse is a short Python example I wrote in 2016 for indenting single-line SQL queries into a readable form. The repository holds a single file, and the sqlparse library does the work.
Purpose
SQL queries inside application code or in log records often sit on one long line. A query that joins several tables and has many conditions is hard to read and debug in that form. I wrote this example to note down the shortest way, from within Python, to turn a query into a neatly indented version with its keywords in upper case. It is part of a small series, together with the HTML, CSS, JavaScript, XML and JSON indenting examples I made on the same day.
How it works
The script defines a simple sample select query that picks three columns and has a single condition. This query is passed to the sqlparse library's format function with two settings. reindent=True re-indents the query and puts each part on its own line. keyword_case='upper' turns SQL keywords such as select, from and where into upper case. The result is printed straight to the screen.
Key features
- It puts each part of the query on its own line, which makes the structure visible.
- It turns keywords into upper case, which separates the query language from table and column names.
- It does not run the query; it only formats it as text, so no database connection is needed.
Technical stack
The code is written in Python and its only external dependency is the sqlparse library. The example uses Python 2 syntax, where print is written without parentheses.
Status
This is a note-style example and has not been updated since 2016. Turning the print line into a function call is enough to run it on Python 3.
Use cases
- It can be used to make a long query taken from log records readable before looking into it.
- It helps show queries built in code in a tidy form when adding them to documentation or a bug report.
- It can serve as a starting point when adding SQL formatting to another Python tool.
- Category
- Developer tools
- Year
- 2016
Technologies
- Python
- SQL
Links
- GitHub https://github.com/muslu/SQL_Parse