22

I'd like to reformat some SQL statements that are a single string with newlines in to something that's much easier to read.

I don't personally know of a good coding style for indenting SQL - how should nested queries / where clauses / left joins / etc by represented to maximise readability?

Has anyone seen a pretty-printing algorithm that does this already? In Python would be even better.

Helen
  • 71,797
  • 10
  • 199
  • 256
Simon Willison
  • 15,062
  • 5
  • 33
  • 43

5 Answers5

41

You can try sqlparse. It's a Python module that provides simple SQL formatting. A online demo is available here.

JL Peyret
  • 9,051
  • 2
  • 41
  • 63
Andi Albrecht
  • 553
  • 4
  • 4
3

I personally use SQL Inform for quick SQL formating, which is written in Java and is unfortunately not open source, so there is no access to the underlying algorithm.

James McMahon
  • 46,983
  • 63
  • 201
  • 278
3

Perhaps part of the difficulty in finding a tool is that there are so many different "standard" SQL formatting conventions. Here are two SO questions that describe people's preferences:

Community
  • 1
  • 1
yukondude
  • 23,233
  • 13
  • 47
  • 56
2

I have previously used SQL Complete by Devart for formatting SQL, but now there is a free online SQL beautifier powered by SQL Complete - SQL Formatter it is really feature rich and easy to use even for a beginner.

-2

Don't know if it answers your question, but I generally use this strategy

SELECT what1, what2, etc,
FROM table
WHERE condition
  AND condition
  AND condition
ORDER BY whatever

But that's just me. I don't think proper automatic tools exist.

Stefano Borini
  • 132,232
  • 95
  • 283
  • 413