Last active
March 20, 2025 21:10
-
-
Save louisswarren/e4d87c04dad85fb2f3a2fa0304d42ff7 to your computer and use it in GitHub Desktop.
My coding style for SQL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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 | |
) and | |
( | |
a.important = 1 | |
or | |
a.possible = 1 and | |
b.required = 1 | |
) | |
), | |
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