Note that there are some explanatory texts on larger screens.

plurals
  1. POSQL formatting standards
    text
    copied!<p>In my last job, we worked on a very database-heavy application, and I developed some formatting standards so that we would all write SQL with a common layout. We also developed coding standards, but these are more platform-specific so I'll not go into them here.</p> <p>I'm interested to know what other people use for SQL formatting standards. Unlike most other coding environments, I haven't found much of a consensus online for them.</p> <p>To cover the main query types:</p> <pre><code>select ST.ColumnName1, JT.ColumnName2, SJT.ColumnName3 from SourceTable ST inner join JoinTable JT on JT.SourceTableID = ST.SourceTableID inner join SecondJoinTable SJT on ST.SourceTableID = SJT.SourceTableID and JT.Column3 = SJT.Column4 where ST.SourceTableID = X and JT.ColumnName3 = Y </code></pre> <p>There was some disagreement about line feeds after <code>select</code>, <code>from</code> and <code>where</code>. The intention on the select line is to allow other operators such as "top X" without altering the layout. Following on from that, simply keeping a consistent line feed after the key query elements seemed to result in a good level of readability. </p> <p>Dropping the linefeed after the <code>from</code> and <code>where</code> would be an understandable revision. However, in queries such as the <code>update</code> below, we see that the line feed after the <code>where</code> gives us good column alignment. Similarly, a linefeed after <code>group by</code> or <code>order by</code> keeps our column layouts clear and easy to read.</p> <pre><code>update TargetTable set ColumnName1 = @value, ColumnName2 = @value2 where Condition1 = @test </code></pre> <p>Finally, an <code>insert</code>:</p> <pre><code>insert into TargetTable ( ColumnName1, ColumnName2, ColumnName3 ) values ( @value1, @value2, @value3 ) </code></pre> <p>For the most part, these don't deviate that far from the way MS <a href="http://en.wikipedia.org/wiki/SQL_Server_Management_Studio" rel="nofollow noreferrer">SQL Server Managements Studio</a> / query analyser write out SQL, however they <em>do</em> differ.</p> <p>I look forward to seeing whether there is any consensus in the Stack Overflow community on this topic. I'm constantly amazed how many developers can follow standard formatting for other languages and suddenly go so random when hitting SQL.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload