4 ms·
This is the style I've settled on lately, where all the major keywords are left-aligned and the clauses are consistently indented. It uses a bit more vertical s
by saila 6y ago
This is the style I've settled on lately, where all the major keywords are left-aligned and the clauses are consistently indented. It uses a bit more vertical space, but I find it easier to read than any other formatting style I've seen (in the wild or produced by formatters).
select
a.foo,
b.bar,
g.zed
from
alpha a
join
beta b
on b.alpha_id = a.id
left join
gamma g
on g.beta_id = b.id
where
a.val > 1
and b.col < 2
order by
a.foo
It's really easy, for me anyway, to get an overview of the query with this style compared to styles that are more cramped or that are inconsistently wrapped/indented.
For simpler queries, I think this is okay too, but only if the clauses easily fit on a single line:
select ...
from ...
join ...
where ...
- Icathian 6y ago10 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.
- u801e 6y agoI'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.
- dbatten 6y agoMy company style guide explicitly specifies this. https://github.com/republicwireless-open/sql-style-guide https://github.com/republicwireless-open/sql-style-guide I think Mozilla's does as well.
- croes 6y agoIt's also easier if you want to comment out certain parts of your code during debugging.
- scottmcdot 6y agoOn this, I like to also use Where 1 = 1 And... And... Which makes it easy to comment out specific filters.
- Tostino 6y agoYup, my code is littered with WHERE true AND ...
- ianmcgowan 6y agoI 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 ...
- mobjack 6y agoThat is my preferred style. If there are many joins, I could also add more indention to show what is being joined to what.