What is the accepted practice for indenting SQL statements? For example, consider the following SQL statement:
SELECT column1, column2
FROM table1
WHERE column3 IN
(
SELECT TOP(1) column4
FROM table2
INNER JOIN table3
ON table2.column1 = table3.column1
)
How should this be indented? Many thanks.
That's how we would do it here:
Our idea is: keep sql keywords in lower case and put all changing (and therefore "more interesting") things like table or column names in upper case. The code might look a bit "blown up" here, but it increases readability if you have complex queries with longer names (incl. schema etc.) much longer than in this example. And: indent all objects according to their "level".
I like to have all "," in front, this way I never search them when an error at line X from the SQL editor.
This is an example for those who do not use this type of writting SQL statement. Both contain an error of a missing comma.
I found easier and more quick at the first example. Hope this example show you more my point of view.
Example indenting a very very very complex SQL:
As most above have lined up the return column names, I find lining up tables names and conditions helps readability a lot.
And for when join conditions get long.
I would format like this:
or like this:
This is my normal preference:
Although stackoverflow messes up the formatting with an extra leading space, so I put in some periods so you can see the actual formatting...