Live data from Hacker News

Writing more legible SQL

craigkerstiens.com

1–10 of 168 posts

Re: Writing more legible SQL

#2
Am I the only one to see or missing obviously. The following is wrong, where clause has table name (baz)?

    SELECT foo,
       bar
    FROM baz
    WHERE foo > 3
      AND baz =  'craig.kerstiens@gmail.com'
Edit: Technically you can have a column name exactly same as table name, however I am finding it hard to find difference between the two queries presented.

Re: Writing more legible SQL

#3
I loathe wide lines. I think it's much easier to mentally parse vertical lists of things and I write my SQL much like this.

In PHP / Python / Go when inlining SQL I also line up sequential items indentation with spaces (which most editors do by default when hitting enter inside a multi line string).

Nice to see this codified. I really just wish I would have worked more in my career on teams that care as much about readability and comprehension in 6+ months as I do.

Hopefully more people will follow the advice in the article and write cleaner, easier to mentally parse SQL.

Re: Writing more legible SQL

#5

Am I the only one to see or missing obviously. The following is wrong, where clause has table name (baz)? SELECT foo, bar FROM baz WHERE foo > 3 AND baz = 'craig.kerstiens@gmail.com' Edit: Technically you can have a column name exactly same as table name, however I am finding it hard to find difference between the two queries presented.

Yeah, definitely a typo in the example, will fix.

Re: Writing more legible SQL

#9
post #8

I prefer my own style where comma is placed before every column. It makes columns, subqueries and case expressions line up nicely, especially when you have 15 columns or more.

Yeah, I've definitely seen this and tried it myself. Visually for some reason, it just pains me too much. It does make removing lines much easier though so I can understand the appeal.

Re: Writing more legible SQL

#10
Here is how I write SQL:

    select
        t1.col1,
        t2.col2,
        t3.col3
    from table1 t1
        join table2 t2 on t1.col2 = t2.col1
        join table3 t3 on
            t1.col3 = t3.col1 and
            t3.col2 = something_else
    where
        t1.col1 > 0 and
        t2.col2  t1.col4
    order by col2
    limit 100
So:

1. SQL capitalization is not sacred. I lowercase everything.

2. I just indent subclauses, with four spaces, like I indent other languages. I don't go out of my way to line up things vertically.

3. Conjunctions like "and" are put at the end of a line, like a comma, not at the beginning. I think it lines things up better vertically.

4. I try to keep lines short, but I also try to keep it from getting needlessly long vertically. So if the statement is short and simple, I might fold some things back onto one line, like:

    select col1, col2, col3
    from table1
    where col1 = something_or_other

or even:

   select * from table1 where col1 = something
Post reply on HN