Search code examples
sqlcoding-styleindentation

SQL Statement indentation good practice


What is the accepted practice for indenting SQL statements?

How should this example be indented?

SELECT column1, column2
FROM table1
WHERE column3 IN
(
SELECT TOP(1) column4
FROM table2
INNER JOIN table3
ON table2.column1 = table3.column1
)

Solution

  • SELECT column1
         , column2
    FROM table1
    WHERE column3 IN
    (
        SELECT TOP(1) column4
        FROM table2
        INNER JOIN table3
        ON table2.column1 = table3.column1
    )
    

    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.

    SELECT sdcolumn123
     , dscolumn234
     , sdcolumn343
     , ffcolumn434
     , sdcolumn543
     , bvcolumn645
      vccolumn754
     , cccolumn834
     , vvcolumn954
     , cvcolumn104
    FROM table1
    WHERE column3 IN
    (
        ...
    )
    
    SELECT sdcolumn123, dscolumn234, asdcolumn345, dscolumn456, ascolumn554, gfcolumn645 sdcolumn754, fdcolumn845, sdcolumn954, fdcolumn1054
    FROM table1
    WHERE column3 IN
    (
        ...
    )
    

    I found easier and more quick at the first example. Hope this example show you more my point of view.