Re:Best practices for writing SQL queries
by ianmcgowan on Saturday April 10, 2021 @07:11PM
(#26766139)
I do this style too, but think of each new row as basically a new table being added to the query (especially if it's a query, which may go over several rows and is indented):
from
alpha a
inner join beta b on b.id = a.id
left outer join gamma g on g.id = a.id
left outer join (
select z.id, count(\*) as cnt from zeta z
) delta on delta.id = a.id
where
...
Re:Best practices for writing SQL queries
by mobjack on Saturday April 10, 2021 @08:17PM
(#26766540)
That is my preferred style.
If there are many joins, I could also add more indention to show what is being joined to what.
Re:Best practices for writing SQL queries
by dbatten on Saturday April 10, 2021 @05:02PM
(#26765090)
My company style guide explicitly specifies this.
https://github.com/republicwireless-open/sql-style-guide
I think Mozilla's does as well.
It's also easier if you want to comment out certain parts of your code during debugging.
Re:Best practices for writing SQL queries
by scottmcdot on Saturday April 10, 2021 @06:28PM
(#26765787)
On this, I like to also use
Where 1 = 1
And...
And...
Which makes it easy to comment out specific filters.
Re:Best practices for writing SQL queries
by Tostino on Saturday April 10, 2021 @07:08PM
(#26766111)
Yup, my code is littered with WHERE true AND ...
Re:Best practices for writing SQL queries
by Icathian on Saturday April 10, 2021 @04:31PM
(#26764871)
10 years messing with data across 5 major flavors of sql and this is the format I've settled on and advocated for my team. It seems to flow the best and be easiest for people to get used to.
I've found that using hanging indents and using prefixed binary operators, like you did here, is the most readable form and when adding additional clauses, makes for a readable diff.
For simpler queries, I think this is okay too, but only if the clauses easily fit on a single line: