Skip to content

Instantly share code, notes, and snippets.

@louisswarren
Created December 3, 2022 00:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save louisswarren/e4d87c04dad85fb2f3a2fa0304d42ff7 to your computer and use it in GitHub Desktop.
Save louisswarren/e4d87c04dad85fb2f3a2fa0304d42ff7 to your computer and use it in GitHub Desktop.
My coding style for SQL
/* Idea:
* Use 8 spaces for indenting the body of clauses
* Use 4 spaces for all other indentation
* Set your editor to expand tab to 4 spaces
This is highly readible while minimising effort while writing.
Indentation that requires manual character-level alignment would be
extremely painful (for me).
*/
with
rawtbl as (
select distinct
a.foo,
b.bar,
case
when c.baz is null then
0
when c.baz < 100 then
c.baz
else
100
end as bazclamp
from a
inner join b
on a.idx = b.idx
left join c
on a.t1 = c.t1 and
a.t2 = c.t2
where a.is_deleted 0 = and
exists (
select 1
from d
where d.a_idx = a.idx
)
),
select foo,
bar,
sum(bazclamp) as baztotal
from rawtbl
group by foo, bar
having min(bazclamp) > 0
order by 3 desc, 1, 2
/*
It's unfortunate that "by" is compulsory with GROUP BY and ORDER BY,
making them not fit in 7 characters.
If I am grouping or ordering by many columns, I put "by" on its own line.
*/
select *
from widetable
order by
idx,
apples,
pears desc,
oranges
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment