SELECT ...
FROM Customers AS c
INNER JOIN (SELECT * FROM Classification WHERE CustomerType = 'Standard') AS cf
ON c.TypeCode = cf.Code
INNER JOIN SalesReps s ON cf.SalesRepID = s.SalesRepID
SELECT ...
FROM Customers AS c
INNER JOIN Classification AS cf ON c.TypeCode = cf.Code
INNER JOIN SalesReps AS s ON cf.SalesRepID = s.SalesRepID
WHERE cf.CustomerType = 'Standard'
SQL Server
will treat both queries the same.
These queries are identical performance-wise. You can freely interchange ON
, WHERE
and inline view conditions: the SQL Server
's optimizer is smart enough to figure out the best plan.
The first query is more easily convertable into an OUTER JOIN
whenever the need arises, however, in this case it may be better worded as this:
SELECT ...
FROM Customers AS c
INNER JOIN -- or OUTER JOIN
Classification AS cf
ON cf.Code = c.TypeCode
AND cf.CustomerType = 'Standard'
INNER JOIN -- or OUTER JOIN
SalesReps AS s
ON s.SalesRepID = cf.SalesRepID
When writing the queries, I try to write them so that the key nature is obvious from the query.
If there a single column key on cf.code
, I'd use this:
SELECT ...
FROM Customers AS c
INNER JOIN
Classification AS cf
ON cf.Code = c.TypeCode
INNER JOIN
SalesReps AS s
ON s.SalesRepID = cf.SalesRepID
WHERE cf.CustomerType = 'Standard'
If the key is cf (Code, CustomerType)
, then this one:
SELECT ...
FROM Customers AS c
INNER JOIN
Classification AS cf
ON cf.Code = c.TypeCode
AND cf.CustomerType = 'Standard'
INNER JOIN
SalesReps AS s
ON s.SalesRepID = cf.SalesRepID
, and if the key is cf (CustomerType, Code)
, then this one:
SELECT ...
FROM Customers AS c
INNER JOIN
(
SELECT *
FROM Classification
WHERE CustomerType = 'Standard'
) AS cf
ON cf.Code = c.TypeCode
INNER JOIN
SalesReps s
ON s.SalesRepId = cf.SalesRepID
A little side note: in MySQL
, inline views are much less efficient than the joins, so I'd won't use them in this case in MySQL
.
This is not the case for SQL Server
, though.