here’s my SQL coding style, briefly explained
if i have not explained something clearly, please ask me to clarify
if you’d like to add to the topic with your own preferences, please do
when writing SQL, i like to align keywords and expressions against a vertical “river” of space
like this –
| |
| |
KEYWORDS | | expressions
---> | | <---
| |
keywords right aligned on the left side of the river, expressions left aligned on the right
so for example –
SELECT table1.jobno
, table1.fixed
, COALESCE(table1.cost, table2.cost) AS cost
FROM table1
LEFT OUTER
JOIN table2
ON table2.jobnumber = table1.jobno
AND table2.status = 'ok'
minor exceptions are allowed such as LEFT OUTER extending through the space, but note how JOIN and ON and AND are aligned to make the river easier to see
this vertical river of space is a strong visual aid in understanding the structure of an SQL statement
leading commas (which is a separate discussion, and a good one) are placed on the left side of the river to stand out just like ANDs and ORs do, re-inforcing the structure, with elements at the same logical level stacked, rather than listed
(yes this can make for some tall SELECT clauses)
notice how i’ve structured the join –
FROM table1
LEFT OUTER
JOIN table2
ON table2.jobnumber = table1.jobno
some people write this as –
FROM table1
LEFT OUTER
JOIN table2
ON table1.jobno = table2.jobnumber
of course, these are exactly equivalent, but notice how your eyes (and brain) have to do a quick switcheroo
(verify this yourself when you next read someone else’s query and they’ve done it that way)
so when writing a JOIN, i align that new joined table’s columns on the left, and thus make it easier to instantly see how it’s being joined to what went before
this is re-inforced when there are additional join conditions for that table –
FROM table1
LEFT OUTER
JOIN table2
ON table2.jobnumber = table1.jobno
AND table2.status = 'ok'
notice how table2 and its columns are easy to see as a group
and the joined column sticks out on the right, making it easier to reference the table above that it’s joining to
finally, indentation for nested structure levels
i won’t say much beyond the fact that everything shifts over!
for example, a subquery –
SELECT table1.jobno
, table1.fixed
, spec.price
, COALESCE(table1.cost, table2.cost) AS cost
FROM table1
LEFT OUTER
JOIN table2
ON table2.jobnumber = table1.jobno
AND table2.status = 'ok'
LEFT OUTER
JOIN ( SELECT job
, MAX(price) AS price
FROM table3
WHERE estimate = 'y'
GROUP
BY job
) AS spec
ON spec.job = table1.jobno
a subquery in the FROM clause is sometimes called a derived table
notice where the ON clause for the derived table is aligned
see the second river?