{"id":781,"date":"2010-01-21T00:00:00","date_gmt":"2010-01-21T00:00:00","guid":{"rendered":"https:\/\/test.simple-talk.com\/uncategorized\/laying-out-sql-code\/"},"modified":"2021-09-29T16:22:01","modified_gmt":"2021-09-29T16:22:01","slug":"laying-out-sql-code","status":"publish","type":"post","link":"https:\/\/www.red-gate.com\/simple-talk\/databases\/sql-server\/t-sql-programming-sql-server\/laying-out-sql-code\/","title":{"rendered":"Laying out SQL Code"},"content":{"rendered":"<div id=\"pretty\">\n<p><i>&#8216;This article is just rudimentary. What are u professional guys fussing about?&#8217;<br \/>\n<\/i>Anonymous comment on Bob Sheldon&#8217;s article &#8216;Transact SQL formatting standards&#8217;<\/p>\n<p class=\"start\">\u00a0SQL, unlike a language such as Python, doesn&#8217;t require any formatting, or laying out, of its code in order\u00a0 to compile and run. On the other hand, the layout of SQL is important because SQL was always intended to be close to a real declarative human sentence, with phrases for the various parts of the command. It was written in the days when it was considered that a computer language should be easy to understand. \u00a0Laying SQL out carefully, and choosing sensible object names helps greatly.<\/p>\n<p>You may feel compelled to format SQL code as if it were Pascal or Java, for the reason that you may have come from a Pascal background and find any other way of doing it disconcerting. Every language marks its practitioners for keeps. ForTran programmers tend to write thin columns of abbreviated code, \u00a0Java programmers often like their SQL code to be in lower case, and BASIC programmers never seem to get used to multi-line strings. \u00a0In fact, it is often possible to detect what language a database developer first cut his teeth on from looking at the way they format SQL. Because we all have had different influences on the way we write code, there will never be any agreement about the way that code is laid out.<\/p>\n<p>There is no single correct way of laying out SQL or naming your database objects. However, when a developer is spending forty hours a week staring at SQL code, he or she gets to like it laid out to a particular style. Code in this style will be considerably easier for them to read and understand. Other people&#8217;s code looks all wrong.\u00a0 This only causes difficulties when team members find no way of agreeing on a format, and much time is wasted lining things up or changing the case of object names before starting to work on existing code.<\/p>\n<p>Why revisit this topic? It has been discussed in a number of places and was the subject of a book (Joe Celko&#8217;s <strong>SQL Programming Style)<\/strong>. \u00a0 The reason I&#8217;m interested is that a growing number of applications have been devised that will do this automatically, and <a href=\"http:\/\/extras.sqlservercentral.com\/prettifier\/prettifier.aspx?skin=st\">I even wrote one myself in SQL <\/a>that did this in a rudimentary way. The subject is even more interesting to publishers such as Simple Talk, because they have to render SQL code for publication\u00a0 in a way that is generally acceptable. It isn&#8217;t easy to come up with the detail for doing this.<\/p>\n<p>There are several things that need to be decided before you start a development project. One job that is worth tackling is to produce a style guide before any code is cut. Any style guide should, I think, cover Object Naming Conventions and Code Layout. I would keep the topic of structured code-headers, and code-portability, separate. Although ISO\/IEC 11179 will help a great deal in defining a common language for talking about metadata, it is, inevitably,\u00a0 less prescriptive when discussing the practicalities of a style guide for a project. I have not found any adopted standard at all for layout, so I hope I can help with some suggestions for this in this article.<\/p>\n<h1>Object Naming Conventions.<\/h1>\n<p>Object naming is really a different subject altogether from layout, and it is impossible to refactor the naming of SQL objects automatically as one can the layout.\u00a0 It has to be done right from the start. Because object-naming is so bound-up with our culture, it causes many arguments in development teams.\u00a0 There are standards for doing this (ISO\/IEC 11179-5. Naming and identification principles for data elements), but everyone likes to bring their own familiar rituals to the process.\u00a0 Here are a few points that cause arguments.<\/p>\n<div class=\"indent\">\n<h2>Tibbling.<\/h2>\n<p class=\"indented\">The habit most resistant to eradication is &#8216;Tibbling&#8217;, the use of reverse Hungarian notation, a habit caught from starting out with Microsoft Access.\u00a0 &#8216;Tibbling&#8217; is named after the habit of prefixing the name of a table with the &#8216;tbl&#8217; prefix, thereby making it difficult to pronounce. A tibbler will take a table that should be called &#8216;Node&#8217;, and call it &#8216;<b>tblNode<\/b>&#8216;.\u00a0 Stored procedures will be called something like <b>spCreateCustomer <\/b>and table-valued functions will be called <b>tvfSubscription<\/b>. This makes talking about your data difficult.\u00a0 &#8216;Tibbling&#8217; is now\u00a0rather entrenched at Microsoft, in a mutated version that gives a PK_, FK_ IX_SP_or DF_ prefix to object names (but not mercifully to tables yet),\u00a0so I doubt\u00a0 that it will ever be eradicated amongst SQL Server programmers. It has never been part of any national or international standard for naming data objects.<\/p>\n<h2>Pluralising<\/h2>\n<p class=\"indented\">A Pluraliser will always name a table after a quantity of entities rather than an entity.\u00a0 The <b>Customer<\/b> table will be called <b>Customers<\/b>, and <b>Invoice <\/b>will be <b>Invoices.<\/b> \u00a0Ideally, the use of a collective name for the entities within a table is best, but failing that, the singular noun is considered better than the plural.<\/p>\n<h2>Abbreviating (or abrvtng)<\/h2>\n<p class=\"indented\">An Abbreviator usually picks up the habit from interpreted procedural programs of trying to abbreviate all names, under the mistaken belief that the code will run faster, take less space or be, in some mystical sense, more efficient. Heaving out the vowels (the &#8216;vowel movement&#8217;) is a start, so that <b>Subscription <\/b>becomes <b>Sbscrptn<\/b>, but the urge towards the mad extreme will end up with <b>Sn<\/b>. I&#8217;ve heard of this being call &#8216;Custing&#8217;, after the habit of using the term <b>Cust<\/b> instead of <b>Customer<\/b>. To them, I dedicate the following routines<\/p>\n<div class=\"indented\">\n<pre class=\"theme:ssms2012 lang:tsql\">CREATE TABLE ## ( # INT ) \r\nDECLARE @ INT\u00a0 set @=8\r\nINSERT\u00a0 INTO ##\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 ( # )\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 SELECT\u00a0 @%2\r\nSELECT\u00a0 *\r\nFROM\u00a0\u00a0\u00a0 ##\r\n<\/pre>\n<\/div>\n<p class=\"indented\">This habit came from the old ForTran days when you could only use 6 characters at the most. SQL 92 allows 18 characters, but SQL Server has no limit.<\/p>\n<h2>[Escaping]<\/h2>\n<p class=\"indented\">Because spaces are not allowed in object names, unless the name is escaped, SQL names need some way of separating words.\u00a0 One could write <b>customerAccounts<\/b>, <b>CustomerAccounts<\/b>, <b>customer_Accounts<\/b> or <b>Customer_Accounts<\/b>.\u00a0 Yes, you need to make up your mind.<\/p>\n<p class=\"indented\">Because desktop databases such as Access are more liberal about the character set you can use for object names, the idea came of &#8216;escaping&#8217;, &#8216;quoting&#8217;, or delimiting \u00a0such names so that they could be copied without modification into a full relational database.\u00a0 Those of us who take trouble to write legal SQL object names find the rash of square brackets that are generated by SSMS acutely irritating. Here is some code that really runs perfectly happily in SQL Server, purely because of the use of escaping with square brackets.<\/p>\n<div class=\"indented\">\n<pre class=\"theme:ssms2012 lang:tsql\">\/* we see if we can execute a verse of Macauley's famous poem 'Horatius'. *\/\r\n\u00a0\r\n--create a table with a slightly unusual name\r\ncreate table [many a stately market-place;\r\n\u00a0\u00a0\u00a0 From many a fruitful plain;\r\n\u00a0\u00a0\u00a0 From many a lonely hamlet,]\r\n\u00a0\u00a0\u00a0 (\r\n[The horsemen and the footmen\r\n\u00a0\u00a0\u00a0 Are pouring in amain] int,\r\n\u00a0\u00a0\u00a0 [, hid by beech and pine,] varchar(100)\r\n)\u00a0\u00a0\u00a0 \r\n--put a value into this table\r\ninsert into [many a stately market-place;\r\n\u00a0\u00a0\u00a0 From many a fruitful plain;\r\n\u00a0\u00a0\u00a0 From many a lonely hamlet,] ([The horsemen and the footmen\r\n\u00a0 \u00a0\u00a0Are pouring in amain], [, hid by beech and pine,])\r\n\u00a0\u00a0\u00a0 Select 1,'an eagle's nest, hangs on the crest\r\n\u00a0\u00a0\u00a0 Of purple Apennine;'\r\n\u00a0\r\n\/* now, with that preparation work done, we can execute the third verse *\/\r\nSelect\u00a0\u00a0\u00a0 \r\n\u00a0\u00a0\u00a0 [The horsemen and the footmen\r\n\u00a0\u00a0\u00a0 Are pouring in amain]\r\n\u00a0\u00a0\u00a0 From [many a stately market-place;\r\n\u00a0\u00a0\u00a0 From many a fruitful plain;\r\n\u00a0\u00a0\u00a0 From many a lonely hamlet,]\r\n\u00a0\u00a0\u00a0 Where[, hid by beech and pine,]\r\n\u00a0\u00a0\u00a0 Like 'an eagle's nest, hangs on the crest\r\n\u00a0\u00a0\u00a0 Of purple Apennine;'\r\n\u00a0\r\n<\/pre>\n<\/div>\n<p class=\"indented\">It is true that &#8216;delimited&#8217; names used to be handy \u00a0for non-Latin languages such as Chinese, but nowadays you can use Unicode characters for names so this compiles perfectly happily<\/p>\n<div class=\"indented\">\n<pre class=\"theme:ssms2012 lang:tsql\">CREATE TABLE \u00e4\u00b8\u00ad\u00e5\u00e6\u00b8\u00e6\u00e5\u00ba\u00ab\u00e8\u00a1\u00a8\r\n(\u00e6\u00e7\u00e4\u00b8\u00bb\u00e9\u00b5 CHAR(2) NOT NULL PRIMARY KEY, \r\n\u00a0\u00e6\u00e7\u00e6\u00b8\u00e6\u00e5 INTEGER NOT NULL\r\n\u00a0 CHECK (\u00e6\u00e7\u00e6\u00b8\u00e6\u00e5 &gt; 0));\u00a0 \r\n<\/pre>\n<\/div>\n<p class=\"indented\">Herein lies another horrifying possibility. SQL Server will allow you to use &#8216;shapes&#8217;.<\/p>\n<div class=\"indented\">\n<pre class=\"theme:ssms2012 lang:tsql\">CREATE TABLE \"\u00e2\u00e2\u00a6\u00e2\u00a9\u00e2\" ( \"\u00e2\u00e2\u00ac\u00e2\u00b4\u00e2\" nvarchar(10)) \r\nDECLARE @ nvarchar(10)\u00a0 set @='\u00e2'\r\nINSERT\u00a0 INTO \"\u00e2\u00e2\u00a6\u00e2\u00a9\u00e2\"\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 ( \"\u00e2\u00e2\u00ac\u00e2\u00b4\u00e2\" )\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 SELECT\u00a0 replicate(@,5)\r\nSELECT\u00a0 *\r\nFROM\u00a0\u00a0\u00a0 \"\u00e2\u00e2\u00a6\u00e2\u00a9\u00e2\"\r\n<\/pre>\n<\/div>\n<h2>Restricting<\/h2>\n<p class=\"indented\">A habit that has crept into SQL from ex-Cobol programmers, I believe, is the use of a very restricted vocabulary of terms. \u00a0This is rather like the development of cool street-argot with a highly restricted set of 400 words, rather than the 40,000 that are within the grasp of the normal adult.\u00a0 With sql, this typically uses words like &#8216;GET&#8217;, &#8216;PUT&#8217;\u00a0 or &#8216;SAVE&#8217; in a variety of\u00a0 SQL is perfectly happy to oblige, even though the results are difficult to understand.\u00a0<\/p>\n<p class=\"indented\">Taking this to extremes, this code is perfectly acceptable to SQL Server.<\/p>\n<div class=\"indented\">\n<pre class=\"theme:ssms2012 lang:tsql\">--first create a GetDate schema\r\nCREATE SCHEMA GetDate\r\n--and a GetDate table to go in it.\r\nCREATE TABLE GetDate.GetDate\r\n(\r\nGetDate DATETIME,\r\n[GetDate GetDate] DATETIME\r\n)\r\nGO\r\n--and a function called GetDate\r\nCREATE FUNCTION GetDate()\r\nRETURNS TABLE\r\nAS RETURN\r\n(\r\n\u00a0\u00a0\u00a0\u00a0\u00a0 SELECT GetDate() AS [GetDate]\r\n)\r\nGO\r\n-- Now we can write some startlingly silly code\r\nINSERT INTO GetDate.GetDate(GetDate.GetDate.GetDate.GetDate, [GetDate GetDate])\r\n\u00a0\u00a0\u00a0\u00a0\u00a0 SELECT GetDate() AS GetDate, GetDate FROM GetDate()\r\n--but we can do far far siller stuff if we wanted purely because there is no restiction on what goes between angle-brackets\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \r\nCREATE FUNCTION [GetDate.GetDate.GetDate.GetDate\r\nGetDate.GetDate.GetDate.GetDate\r\nGetDate.GetDate.GetDate.GetDate]()\r\nRETURNS TABLE\r\nAS RETURN\r\n(\r\n\u00a0\u00a0\u00a0\u00a0\u00a0 SELECT GetDate() AS [GetDate]\r\n)\r\nGO\r\n\u00a0\r\nINSERT INTO GetDate.GetDate(GetDate.GetDate.GetDate.GetDate, [GetDate GetDate])\r\n\u00a0\u00a0\u00a0\u00a0\u00a0 SELECT GetDate() AS GetDate, GetDate FROM [GetDate.GetDate.GetDate.GetDate\r\nGetDate.GetDate.GetDate.GetDate\r\nGetDate.GetDate.GetDate.GetDate]()\r\n<\/pre>\n<\/div>\n<\/div>\n<p>The existing standards for naming objects are more concerned with the way of discussing how you name database objects, and the sort of ways you might document your decisions. However, one can come to a reasonable basis for agreement with the following:<\/p>\n<ul>\n<li>Procedures should be a phrase with singular nouns and a verb, in the present tense,\u00a0 in it to describe what they do<\/li>\n<li>Be consistent with the way you denote word-boundaries (the use of the underline character, the use of a capital letter, or hyphen.)<\/li>\n<li>Tables, sets, views\u00a0 and other collections should use\u00a0 a collective name, a name for a group of entities, such as &#8216;flock&#8217;, &#8216;ledger&#8217;, &#8216;team&#8217;, &#8216;staff&#8217;<\/li>\n<li>Scalar names\u00a0 should be in the singular\n<\/li>\n<li>Any object name should use only commonly-understood abbreviations. Such as ZIP for &#8216;Zone Improvement Plan&#8217;\n<\/li>\n<li>Use standard and consistent \u00a0postfixes \u00a0(eg _ID, _name, _date, _quantity)<\/li>\n<li>Use commonly understood words for relationship tables. (e.g. meeting, booking, marriage, purchase)<\/li>\n<li>names should consist of one or more of the following components\n<ul>\n<li><b>Object Class:<\/b>\u00a0 The name can include just one &#8216;Object class&#8217;\u00a0 which is the terminology used within the community of users of the application. Words like &#8216;Cost&#8217; or\u00a0 purchase<\/li>\n<li><b>Property Term:<\/b> Property terms represent the category of the data. e.g: Total Amount, Date, Sequence, size, height<\/li>\n<li><b>Qualifiers<\/b> These can be used if necessary to describe the data element and make it unique within a specified context, in no particular order, but they must precede the term being qualified. Qualifier terms are optional. Example: Budget Period<\/li>\n<li><b>The Representation term<\/b> This describes the representation of the valid value set of the data element. There should be only one, as the final part of the name, and it should add precision to the preceding terms.\u00a0<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p>It isn&#8217;t always easy to come up with a word to attach to a table.<\/p>\n<p>&#8216;Not all ideas are simply expressed in a natural language, either. For example, &#8220;women between the ages of 15 and 45 who have had at least one live birth in the last 12 months&#8221; is a valid object class not easily named in English&#8217;.<\/p>\n<p>ISO\/IEC 11179-1:2004(E): Page 19<\/p>\n<h1>Coding layout<\/h1>\n<h2>Indenting and line-breaking.<\/h2>\n<h3>Line Breaks<\/h3>\n<p class=\"indented\">SQL code doesn&#8217;t have to be broken into short lines like a Haiku poem. \u00a0Since SQL is designed to\u00a0 be as intelligible as an English sentence, it can be written as an English sentence. It can, of course, be written as a poem, but not as a thin smear down the left-hand side of the query window. The urge to insert large numbers of line-breaks comes from procedural coders where a vertical style is traditional, dating back to the days of FORTRAN and Basic. An advantage of the vertical style is that, when an error just reports a line-number, it takes less time to work out what the problem was. However, it means an over familiarity with the scroll-bar, if the routine runs to any length.<\/p>\n<p class=\"indented\">Indenting and Line-Breaking is done purely to emphasize the structure of SQL, and aid readability.\u00a0 line-breaks have to be inserted at certain points (I rather like to have a line-break at around the 80th character), and they shouldn&#8217;t be mid-phrase. However, to specify that here must always be a line-break between each phrase (before the FROM, ON, and WHERE clause, for example) can introduce an unnecessary amount of white-space into code.\u00a0 Such indenting should never become mere ritual activity to make things look neat, like obsessively painting the rocks in front of your house with white paint.<\/p>\n<p class=\"indented\">Generally, the use of tabs for doing indenting has resulted in indenting that is way too wide.\u00a0 Of course, written text can have wide indents, but it isn&#8217;t done to around eight levels, skidding the text hard-against the right-hand side of the page. Usually, two or three spaces is fine.<\/p>\n<h3>Indenting<\/h3>\n<p class=\"indented\">Code without indenting is very difficult to follow. Indentation follows a very similar practice to a structured document where the left margin is indented according to the nesting of the section heading.\u00a0 It should be a fixed number of spaces for each level of nesting.<\/p>\n<p class=\"indented\">It is at the point where we need to decide what comprises a change in the nesting level that things get difficult.\u00a0 We can be sure that, in a SELECT statement, all clauses are subordinate to the SELECT.\u00a0 Most of us choose to indent the FROM or the WHERE clause at the same level, though, but one usually sees the lists of columns indented.\u00a0 On the other hand, it is quite usual to see AND, ORDER BY, OR, and so on indented to the next level.\u00a0 What rules lie behind the current best-practice? \u00a0Many of us like to have different rules for DDL code, such as CREATE TABLE statements,\u00a0 from DML such as INSERT, UPDATE or SELECT\u00a0 statements.<\/p>\n<h2>Formatting lists<\/h2>\n<p>Lists occur all over the place in code. As in printed text, you can handle them in a number of different ways.\u00a0 If, for example, you are just listing entities then you&#8217;d do it like this. I like many French cheeses, including\u00a0 Abbaye de Belloc, Baguette Laonnaise, Brie de Melun,\u00a0 Calenzana, \u00a0Crayeux de Roncq, Esbareich, Frinault, Mixte, Pave du Berry, Port-Salut, Quercy Petit, Regal de la Dombes, Sainte Maure, Sourire Lozerien, Truffe and Vignotte. Now no typesetter would agree to arrange this in a vertical list because the page would contain too much white space.<\/p>\n<p><i>I like many French cheeses, including <\/i><\/p>\n<ul>\n<li>Abbaye de Belloc,<\/li>\n<li>Baguette Laonnaise,<\/li>\n<li>Brie de Melun,\u00a0<\/li>\n<li>Calenzana, \u00a0<\/li>\n<li>Crayeux de Roncq,<\/li>\n<li>Esbareich,<\/li>\n<li><i>(&#8230;etc &#8230;)<\/i><\/li>\n<\/ul>\n<p>&#8230;and they&#8217;d be most unlikely to want to put commas at the beginning of list elements. However, if the list elements consisted of longer strings, then it would be perfectly acceptable.\u00a0 In the same way, the rules for formatting SQL have to take into account the type of SQL statement being formatted, and the average length of each list element.<\/p>\n<h2>Punctuation<\/h2>\n<p>Commas used as list-separators are often put at the beginning of lines. I realise that it makes the &#8216;commenting out&#8217; of list-members easier during development, but it makes it difficult for those of us that are used to reading English text in books. Commas are at the end of phrases, with no space before them, but if they are followed by a word or phrase on the same line, then there is a space after the comma.\u00a0 Semi-colons are a rather more unfamiliar, but increasing, punctuation mark in SQL.\u00a0 Their treatment should be similar.\u00a0 In development work, one can, and should, do all sorts of wild formatting of SQL, but once it is tested, and\u00a0 &#8216;put to bed&#8217;, it should be tidied up to make it easier for others to understand.<\/p>\n<h2>Capitalisation<\/h2>\n<p class=\"MsoNormal\">Before we start. I&#8217;d like to define what I mean by the various terms<\/p>\n<ul>\n<li>\n<p class=\"MsoNormal\">This_Is_Capitalised<\/p>\n<\/li>\n<li>\n<p class=\"MsoNormal\">This_is_lowercase -or <i>minuscule<\/i><\/p>\n<\/li>\n<li>\n<p class=\"MsoNormal\">this_Is_Camelcase<\/p>\n<\/li>\n<li>\n<p class=\"MsoNormal\">THIS_IS_UPPERCASE-or <em>majuscule<\/em><\/p>\n<\/li>\n<\/ul>\n<p>Schema objects are, I believe, better capitalised. I would strongly advise against using a binary or Case-sensitive collation for the database itself, since this will cause all sorts of unintended errors. A quirk of all European languages is that words mean the same thing whether capital or lower-case letters are used. Uppercase, or majuscule, lettering was used exclusively by the Roman Empire, and lowercase or minuscule was developed later on \u00a0purely as a cursive script. The idea that the case of letters changed the meaning of words is a very recent novelty. \u00a0Of course, one would not expect programmers to be so perverse as to do this sort of thing, but I&#8217;ve seen code that approaches this scale of awfulness in C#<\/p>\n<pre class=\"theme:ssms2012 lang:tsql\">Create database casesensitive\r\nAlter Database casesensitive Collate SQL_Latin1_General_CP1_CS_AS\r\nuse casesensitive\r\ncreate table thing\r\n\u00a0 (\r\n\u00a0\u00a0 Thing int identity(1, 1),\r\n\u00a0\u00a0 tHing Varchar(20),\r\n\u00a0\u00a0 thIng int not null,\r\n\u00a0\u00a0 thiNg float not null,\r\n\u00a0\u00a0 thinG datetime not null\r\n\u00a0 )\r\ninsert into\r\n\u00a0 thing\r\n\u00a0 (tHing, thIng, thiNg, thinG)\r\n\u00a0 select\r\n\u00a0\u00a0\u00a0 'thing', 1, 34.659, '1 Oct 2009'\r\nselect * from thing\r\ndrop table thing\r\n<\/pre>\n<h1>So get off the fence<\/h1>\n<p>I wouldn&#8217;t want to impose my views on anyone else. However, if you are looking for recommendations, here what I usually suggest. I&#8217;d stick to the conventions of<\/p>\n<ul>\n<li>Keeping your database Case-insensitive even if your data has to be case-sensitive, unless you are developing in a language for which this is inappropriate.<\/li>\n<li>Capitalising all the Scalars and Schema object names (e.g. Invoice, Basket, Customer, CustomerBase, Ledger)<\/li>\n<li>\u00a0Uppercasing all reserved words (such as SELECT, WITH, PIVOT, FROM, WHERE)<\/li>\n<li>putting a line-break between list items only when each list item averages more than thirty or so characters.<\/li>\n<li>putting block delimiters (such as BEGIN END)\u00a0 on a new line by themselves, correctly indented<\/li>\n<li>putting line-breaks within SQL statements before the clause (FROM, ON, WHERE, HAVING, GROUP BY) only where it aids clarity in long statements, but not in every case.<\/li>\n<li>use the semi-colon to aid the reading of code, even where SQL syntax states that it is only optional.<\/li>\n<li>using an increased indent for subordinate clauses\u00a0 if the ON, INTO, and HAVING statement is at the start of the line<\/li>\n<\/ul>\n<p>For sheer practicality, I&#8217;d opt for a layout that can be achieved automatically by your favorite code-layout tool (I use <a href=\"http:\/\/www.red-gate.com\/products\/SQL_Refactor\/index.htm?utm_source=simpletalk&amp;utm_medium=article&amp;utm_content=sqllayout&amp;utm_campaign=sqlrefactor\">SQL Refactor<\/a> or <a href=\"http:\/\/www.red-gate.com\/products\/SQL_Prompt\/index.htm?utm_source=simpletalk&amp;utm_medium=article&amp;utm_content=sqllayout&amp;utm_campaign=sqlprompt\">SQL Prompt,<\/a> but there are several others) There is nothing more irritating than to find that someone has trashed a beautifully laid-out procedure by mangling it with a badly-set-up layout tool.<\/p>\n<p>I tend to write my SQL fast and sloppily, to get some initial results quickly, and then refining and rewriting the code until it is fast and efficient. At that point, it is usually a mess and it it very satisfying to run it through a layout tool to smarten it up. In fact, some time ago, before layout tools existed for SQL, I created a stored procedure that tidied up SQL code. It gradually ended up as the <a href=\"http:\/\/extras.sqlservercentral.com\/prettifier\/prettifier.aspx?skin=st\">SQL Prettifier, repurposed to render SQL in HTML<\/a>, and with the formatting part taken out once SQL Refactor appeared.\u00a0 A tool like this can save a lot of inevitable arguments amongst developers as to the &#8216;correct&#8217; way to format SQL code.<\/p>\n<h1>Further reading<\/h1>\n<ul class=\"reference-list\">\n<li><a href=\"http:\/\/www.simple-talk.com\/sql\/t-sql-programming\/transact-sql-formatting-standards-(coding-styles)\/\">Transact-SQL Formatting Standards (Coding Styles)<\/a> Rob Sheldon&#8217;s popular and thorough description of all the issues you need to cover when deciding on the way that SQL code should be laid out<\/li>\n<li><a href=\"http:\/\/www.simple-talk.com\/sql\/t-sql-programming\/sql-code-layout-and-beautification\/\">SQL Code Layout and Beautification<\/a> William Brewer&#8217;s sensible take on the subject, from the perspective of a programmer.<\/li>\n<li><a href=\"http:\/\/metadata-stds.org\/11179\/\">ISO\/IEC 11179<\/a> The international standard\u00a0 for a vocabulary and naming conventions for IT data.<\/li>\n<li><a href=\"http:\/\/books.google.co.uk\/books?id=a9jtyioHfp8C&amp;printsec=frontcover&amp;dq=sql+programming+style&amp;source=bl&amp;ots=Px1sQNx9Zg&amp;sig=KNJM3SzyX4RxxbW_7_OIJd7Dpk8&amp;hl=en&amp;ei=OCdcS8alL5Oy0gSzjJGHBQ&amp;sa=X&amp;oi=book_result&amp;ct=result&amp;resnum=3&amp;ved=0CBcQ6AEwAg#v=onepage&amp;q=&amp;f=false\">Joe Celko&#8217;s SQL Programming Style<\/a> The first book to tackle the subject in depth, and still well-worth reading. You may not agree with all he says, but reading the book will still improve your SQL Coding, as it is packed with good advice.<\/li>\n<\/ul>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>It is important to ensure that SQL code is laid out the best way for the team that has to use and maintain it. Before you work out how to enforce a standard, one has to work out what that standard should be for the application. So do you dive into detail or create an overall logic to the way it is done?&hellip;<\/p>\n","protected":false},"author":154613,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[143531],"tags":[4150,45110,4252],"coauthors":[6813],"class_list":["post-781","post","type-post","status-publish","format-standard","hentry","category-t-sql-programming-sql-server","tag-sql","tag-t-sql-formatting","tag-t-sql-programming"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/781","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/users\/154613"}],"replies":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/comments?post=781"}],"version-history":[{"count":5,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/781\/revisions"}],"predecessor-version":[{"id":71232,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/781\/revisions\/71232"}],"wp:attachment":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/media?parent=781"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/categories?post=781"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/tags?post=781"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/coauthors?post=781"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}