Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Statement indentation good practice [closed]

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.

like image 504
Tangiest Avatar asked Nov 07 '08 14:11

Tangiest


People also ask

Does SQL care about indentation?

Indenting makes SQL easier to follow, as it makes it visually structured. It's recommended not to indent the first line in a multiple line statement, so it would be clear where the statement starts. Make sure that the SQL left margin is indented per the section nesting.

What is proper SQL formatting?

If the name is the same as an SQL keyword, enclose the name within quotation marks. The name of an object in a database for a table or a column should be unique and not too long. Avoid special characters in the name like $, &, * , etc. (use only letters, numbers, and underscores).

Does spacing matter in SQL?

Whitespace is optional in pretty much any language where it is not absolutely necessary to preserve boundaries between keywords and/or identifiers. You could write code in C# that looked similar to your SQL, and as long as the compiler can still parse the identifiers and keywords, it doesn't care.


1 Answers

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.

like image 184
Patrick Desjardins Avatar answered Sep 20 '22 05:09

Patrick Desjardins