views:

1208

answers:

4

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.

+1  A: 

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
+1  A: 

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:

yukondude
A: 

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
+10  A: 

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

Andi Albrecht
That looks like exactly what I was looking for, thanks!
Simon Willison
Thanks for that Andi, this looks pretty cool.
James McMahon
And I just noticed that it is your app.
James McMahon
@nemo: Giving the best to hide myself, but Web2.0 always displays the same picture anywhere ;-)
Andi Albrecht