0

We've encountered the following "issue". I like to use the following writing:

SELECT  Id, Name
FROM    Table1
JOIN    Table2 ON Table1.FK1 = Table2.FK1

but a colleague of mine uses:

SELECT  Id, Name
FROM    Table1 JOIN Table2 
ON      Table1.FK1 = Table2.FK1

Is there a best practice for this? I think it's more convenient if all used tables are alligned.

7
  • Might just be my lack of SQL knowledge, but why is table2 listed twice in your clause instead of comparing to table1? Table2.FK1 = Table2.FK1 Feb 11, 2009 at 15:19
  • It is an error, but doesn't matter for the question...
    – alphadogg
    Feb 11, 2009 at 15:23
  • Of all the things to nitpick about. Seriously? Does it really matter?
    – NotMe
    Feb 11, 2009 at 15:26
  • You've clearly forgotten what segment of the human race you're talking to.
    – chaos
    Feb 11, 2009 at 15:29
  • @Chris Levely: It's just a question dude. If it wouldn't matter, we wouldn't ask it. It's not like our life depends on it off course. Feb 11, 2009 at 15:29

13 Answers 13

9

I prefer the first:

SELECT  Id, Name
FROM    Table1
JOIN    Table2 ON Table1.FK1 = Table2.FK1
0
8

We would actually do:

SELECT Id, Name
    FROM Table1
    JOIN Table2 
        ON Table2.FK1 = Table2.FK1
0
5

The company I work for has an app that uses an object model to generate sql. It generates it with the second syntax most of the time. So lots of joins and then the on conditions. It is extremely frustrating to try and decipher which on condition applies to which table when you have lots of tables.

So I prefer to put the ON clause with the table I'm joining. It makes it much easier to tell what join clauses you've used for a table and what conditional clauses that are a part of your join statement. And getting your joins correct is half the battle. I also prefer the parenthesis.

SELECT primarytable.whatever
FROM primarytable
     INNER JOIN secondarytable ON (primarytable.primarykey = secondarytable.foreignkey)
     INNER JOIN othertable ON (primarytable.foreignkey = othertable.primarykey AND othertable.somefield = 1)
     LEFT OUTER JOIN outertable ON (secondarytable.foreignkey = outertable.primarykey)
WHERE primarytable.somefield IS NOT NULL
1
  • Optionally bring more-complicated ON clauses down to their own (indented) line, and you do it as I do Feb 11, 2009 at 15:47
2

I use something similar to John Price's style:

with Foo as (
    select Id, Name
        from Table1
           join Table2 on 
               Table2.FK = Table1.PK and
               Table2.Foo = Table1.Bar
           join Table3 on 
               Table3.FK = Table1.PK and
               Table3.Foo = Table1.Bar
        where
            Table1.Foo > 1 and
            Table1.Bar < 100
),
Bar as (
    ...
)
select * from Bar;

Some comments:

  • proper indentation of logical blocks: the join goes inside the from, the from inside the select
  • on hangs at the end of the line for proper K&R style. same goes for the with parentheses.

    and also

  • given code colouring, I like lower case keywords much better than UPPER CASE EVERYWHERE.

  • 2
    • I can't say I have a strong opinion re: caps; that just happens to be what our DBA has set out as our standard. I do think indenting logical blocks makes things an awful lot easier to read, though. Feb 11, 2009 at 16:00
    • Caps don't hurt my eyes when reading SQL but I wouldn't appreciate having to write everything like that myself. Feb 11, 2009 at 16:02
    1
    SELECT  Id, Name
    FROM Table1
        JOIN Table2 ON Table2.FK1 = Table2.FK1
    

    I prefer this one. And a beer.

    1

    My style:

    select c.Id, c.Name
    from Parent p
    join Child c on c.ParentID = p.Id
    where p.Id = 123
    
    • If there were a long select-list, I would tend to write each column selected on its own line, or I would write all the columns from one table on one line and all the columns from another table on another line.

    • If there were a long list of conditions in on or where, I would tend to write each condition on its own line.

    Real WTFs:

    • You are not aliasing your tables.
    • You are writing SQL in all caps. I can't read it.
    • You are not using an editor with rudimentary syntax highlighting, thus forcing you to rely on alignment to tell which words mean what.
    3
    • Syntax highlighting helps. Alignment helps. Having both helps a lot; it's synergistic. IMO, I wouldn't bash proper alignment/formatting.
      – alphadogg
      Feb 11, 2009 at 16:05
    • The biggest convention for SQL I've seen is using all caps for the SQL language words. Feb 11, 2009 at 16:06
    • I've seen that convention too, but mostly in COBOL and FORTRAN code. IntelliSense and syntax-highlighting are the modern tools of choice.
      – yfeldblum
      Feb 11, 2009 at 18:26
    0

    I prefer the first, but I've found that a lot of code formatters automatically format to the second.

    0

    I prefer the first version but with some indentation on the JOIN clause to show that it's part of the FROM clause.

    I found this article that gives some pretty good guidelines.

    0

    I prefer the first - it lets me easily comment out joined tables when necessary.

    0

    I always do this:

         SELECT t1.ID, t1.Name
           FROM Table1 t1
     INNER JOIN Table1 t2 ON t1.FK1 = t2.FK1
          WHERE t1.Name = 'Bob'
    

    I find the right-justification of the SQL commands makes it easier to read. Of course if you don't use a monospaced font in your code editor, then this won't work well at all.

    I can't say I know of any "best practice" for this, though.

    0
    select
      Dept.COL1 as "Deptment Name"
    , Emp.COL1 as "Employee Name"
    
    from
    Table1 Dept
    inner join Table2 Emp on Emp.FK1 = Dept.Id
    
    where
        Dept.COL2 = "something"
    and Emp.COL2 = "another"
    

    This is the style I use when developing query to extract data. You can remove any one of the items in the select and where clause by just commenting them out (with the exception of the first one). It is quite handy for debugging.

    If you want them to look pretty and easy to recognize, then line up the "as" in select and "=" in the where clause will definitely help.

    0
    select
        a.Id,
        b.field2,
        b.field3
    from
        table1 a
    join
        table2 b
            on a.Id = b.a_id
    where
        a.field1 = 'hello'
    and b.field2 = 'there'
    

    Using four spaces as a tab, allows "and " to line up in the where clause.

    0
    0

    I like the first out of those two. Our format, however, has more whitespace and we make sure we use brackets.

    SELECT
      x.Id
    , MAX(y.Sales)
    FROM
      [dbo].[Table1] x
    INNER JOIN
      [dbo].[Table2] y ON Table1.Id = Table2.Id
    WHERE
      x.Id = 100
    AND
      x.Name = 'Foo'
    GROUP BY
      x.Id
    HAVING
      COUNT(*) > 1
    

    The formatting tends to grow on most people and the visibility helps a lot. Each important clause is clearly visible.

    EDITED: To alias tables, as per Justice's answer. I do that to, just forgot in this answer. As for all caps, it's a habit from my days of not having great SQL highlighting; it's optional.

    2
    • Actually I think spacing fields on individual lines like that isn't great for small queries but it gets better for larger ones, when you have no chance of squeezing everything onto single lines anyway. Feb 11, 2009 at 15:50
    • It does become slightly more cumbersome with big queries, even though the visibility stays great. One thing that helps is all developers have two or three monitors. Pivot one and you've got lots of space for big queries. Aside, one way this format really helps is commenting out sections when testing
      – alphadogg
      Feb 11, 2009 at 15:58

    Your Answer

    Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

    By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

    Not the answer you're looking for? Browse other questions tagged or ask your own question.