Here are the principles that lead to my current chosen style.
- Indentation should be in the range of 2-4 spaces. Research indicates that people can read and understand code better with an indent in that range than one which is larger or smaller than that.
- When one thing depends on another, indentation should be increased. This makes the core statements obvious.
- When easy, line things up.
- In any list of things, it should be possible to extend the list by pasting new lines on without changing others. In a language like SQL where you can't have trailing commas, that means putting the comma before the line.
- If you wrap, then operators belong at the front of lines. This makes the logical flow easy to see at a glance. (I got this one from Perl Best Practices.)
- SQL is usually case insensitive, so use underscores in field names to avoid ambiguous parses of things like ExpertsExchange and ExpertSexChange.
And here is an example of what this looks like in practice.
SELECT s.foo
, t.bar
, x.baz
, CASE
WHEN s.blat = 'Hello'
THEN 'Greeting'
WHEN s.blat = 'Goodbye'
THEN 'Farewell'
ELSE 'Unknown'
END as blat_type
FROM table1 s
JOIN table2 t
ON s.some_id = t.some_id
AND s.some_type = 'wanted type here'
JOIN (
SELECT *
FROM yet_another_table yat
WHERE yat.reason = 'Subquery demonstration'
) AS x
ON t.another_id = x.another_id
WHERE s.blat = 'some'
AND t.blot = 'condition'
;
If you've never thought about how to format SQL this style is likely to have a few surprises. But try maintaining a lot of SQL that has been formatted in this way, and you should find that it works out quite well.
You can even include comments in your SQL code. Though, nobody ever seems to do that.
ReplyDeleteI tend to comment lightly in general. But I've certainly left lots of comments in SQL when appropriate.
ReplyDeleteMy formatting looks a lot like yours does, with the addition that my CASE blocks have the THEN lines indented once more, as they're dependent on the WHEN lines (much like JOIN - ON). Thanks!
ReplyDeleteStrangely enough I came to a nearly identical style after writing little SQL but lots of JS where the trailing commas become so painful compared to Perl. It was obvious that the SQL would benefit from the same approach.
ReplyDelete