Alex's blog

How do you like your SQL?

Athena Lilith Martin

Published on

There are a number of ways to style SQL code, varying in capitalization, indentation, etc. and frequently the style any given programmer, group, or project uses is very different from the style of their application code. Here's my typical style, as it is nowadays.

I like to capitalize SQL keywords fully, and name all database objects in lower snake case, i.e. SELECT name FROM user_group and not select Name from UserGroup. I also like to make table names singular (user, not users), and I usually don't name constraints. For indentation, I like to try to show the hierarchical structure of the commands, and I tend to break aggressively onto lots of lines. Simple commands I leave on one line, but once it starts to get beyond maybe one join and one WHERE condition, I split it up into a style like this:

SELECT user_group.id, user_group.name, user.id, user.name, user_group_membership.level AS membership_level
  FROM user_group
    LEFT NATURAL JOIN user_group_membership
    INNER JOIN user
      ON user_group_membership.user_id = user.id
  WHERE user_group.name LIKE '%admin%'
    AND user_group.active = true
    AND COUNT(user_group_membership.id) > 0
  ORDER BY user_group.name;
(Yes, this query isn't 100% sensible, it's a style example.)

Note how FROM is the parent of the JOIN clauses, since they're part of answering the same question (Where does the data come from?) and go with it, while WHERE and ORDER BY are separate. It's not completely obvious, but the ANDs are indented as subordinates of WHERE, not column-aligned with the first condition – though I will column-align ORs sometimes (with an extra space between the OR and the condition). I use two-space indentation, but obviously many people have other preferences. Making the first condition part of the WHERE instead of subordinate to it is a slight departure from the pattern, but I feel like otherwise the WHERE feels lonely.

How do you like to style your SQL? I think it would be an interesting comparison to see what different styles look like.

Tagged: