views:

56

answers:

3

Ignoring version, what are the best practices for formatting SQL code?

I prefer this way (method A):

select col from a inner join b on a.id = b.id inner join c on b.id = c.id

a colleague prefers another (method B):

select col from a inner join (b inner join c on b.id=c.id) on a.id = b.id

I'd like to know if there is any difference - the query optimiser appears to generate the same execution plan for both. So maybe it is just readability?

This is the first time I've seen SQL written using method B, does anyone else write SQL like this? Personally I find it really diffacult to read method B.

EDIT: Please not the code is on one line and in upper case to make both more comparable for the purpose of this question.

+1  A: 

Method B is a subselect-like syntax, but it is parsed the same way as method A. There's no harm in using it. I personally prefer method A too, because it can be read in a lineair fashion.

Prutswonder
+1  A: 

I think A is more readable, and most sample code out there uses that style. Both parse the same and product the same query plan, so as far as SQL Server is concerned, there is no difference.

I normally also uppercase keywords and indent for readability:

SELECT col 
FROM a 
  INNER JOIN b 
    ON a.id = b.id  
  INNER JOIN c 
    ON b.id = c.id
Oded
I style it exactly the same way. just didn't in that example.
Mr Shoubs
+1  A: 

My personal preference is

SELECT col1, col2, col3, 
       col4, col5
FROM a
  INNER JOIN b ON a.id = b.id  
  INNER JOIN c ON b.id = c.id
WHERE a.col1 = 1 

I think consistency is key, I prefer your way over your colleagues for readability.

Chris Diver
I prefer to write code this way too, unless there are a lot of join conditions, then I put the on.... on the next line.
Mr Shoubs
I do the same if it begins to look a little big crowded. I prefer upper case for the SQL keywords also, there are only a few keywords and it helps to distinguish them from column/table names. IMO :)
Chris Diver