Skip to content

Instantly share code, notes, and snippets.

@grahamc
Created July 28, 2011 17:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save grahamc/1111950 to your computer and use it in GitHub Desktop.
Save grahamc/1111950 to your computer and use it in GitHub Desktop.
WHERE
email_schedule_subscription.id IS NULL
AND email_schedule.deleted_at IS NULL
AND field_user.deleted_at IS NULL
AND (
(
field_user.timezone_identifier = 'US/Eastern'
AND email_schedule_log.created_at > '2011-07-28 00:00:00'
)
OR (
field_user.timezone_identifier = 'US/Central'
AND email_schedule_log.created_at > '2011-07-27 11:00:00'
)
OR (
field_user.timezone_identifier = 'US/Mountain'
AND email_schedule_log.created_at > '2011-07-27 10:00:00'
)
)
  • SELECT, FROM, WHERE, ORDER BY, GROUP BY, LIMIT, OFFSET, UNION on its own line
  • Columns to select, from, order by, group by on its own line, if AS is present, line them up at the end
  • All SQL operators capitalized
  • The all comparison operators are indented 8 spaces
    • Usage of AND or OR operators replace spaces. Example:
WHERE
        foo.id = bar.foo_id
    AND bar.id = baz.bar_id
     OR bar.id = quux.bar_id
  • Open parenthesis on the same line
  • Close parenthesis on a new line
  • Spaces, not tabs
  • Operators are lined up within its section

More Complicated Example

WHERE
        foo.id = bar.foo_id
    AND (
                bar.id = baz.bar_id
             OR (
                        -- Note that the `=`s are lined up here, but not to the parent section
                        bar.id       = quux.bar_id
                    AND quux.enabled = 1
                 )
         )
  • All column or table listings are on their new line, indented by 4 spaces
  • A single blank line between sections (SELECT block, FROM block, JOIN blocks)
  • JOIN's ON is on the same line as JOIN, and the table name.
  • In a JOIN, put the joined table's columns first in expressions
SELECT
    -- Note these are 4 spaces, not 8
    foo.bar,
    bar.baz,
    baz.quux,

FROM
    -- Note that it is separated by the SELECT by a single line, and the tables begin on a new line
    -- Also note that the AS's line up, even though one of them is very long.
    foo                                AS quux,
    supercalifragilisticexpialidocious AS super,
    baz                                AS zanzibar

LEFT JOIN another_table ON (
        -- Note that another_table comes first.
        another_table.foozle = super.bazzle
    AND another_table.baz    = baz.id
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment