tags:

views:

65

answers:

1

Suppose I have 3 tables.

Sales Rep

  • Rep Code
  • First Name
  • Last Name
  • Phone
  • Email
  • Sales Team

Orders

  • Order Number
  • Rep Code
  • Customer Number
  • Order Date
  • Order Status

Customer

  • Customer Number
  • Name
  • Address
  • Phone Number

I want to get a detailed report of Sales for 2010. I would be doing a join. I am interested in knowing which of the following is more efficient and why ?

SELECT 
    O.OrderNum, R.Name, C.Name
FROM
    Order O INNER JOIN Rep R ON O.RepCode = R.RepCode
            INNER JOIN Customer C ON O.CustomerNumber = C.CustomerNumber
WHERE
    O.OrderDate >= '01/01/2010'

OR

SELECT 
    O.OrderNum, R.Name, C.Name
FROM
    Order O INNER JOIN Rep R ON (O.RepCode = R.RepCode AND O.OrderDate >= '01/01/2010')
            INNER JOIN Customer C ON O.CustomerNumber = C.CustomerNumber
+4  A: 

JOINs must reflect the relationship aspect of your tables. WHERE clause, is a place where you filter records. I prefer the first one.

Make it readable first, table relationships should be obvious (by using JOINs), then profile

Efficiency-wise, the only way to know is to profile it, different database have different planner on executing the query

Wherein some database might apply filter first, then do the join subsquently; some database might join tables blindly first, then execute where clause later. Try to profile, on Postgres and MySQL use EXPLAIN SELECT ..., in SQL Server use Ctrl+K, with SQL Server you can see which of the two queries is faster relative to each other

Michael Buen
+1. Queries become more difficult to read once the WHERE clause starts getting cluttered with a bunch of conditions.
Adam Bernier
+1 - ...and, you're not going to know how the SQL parser is going to construct the query until you do an "explain plan," so the harder-to-read version may not even result in any advantage. If there's a performance problem with the easy-to-read version, you could tweak it, but I wouldn't do anything without the empirical evidence your database system can provide.
Stephen Harmon