Question

When I'm joining three or more tables together by a common column, I'd write my query like this:

SELECT *
FROM   a, b, c
WHERE  a.id = b.id
AND    b.id = c.id

a colleague recently asked my why I didn't do explicit Join Transitive Closure in my queries like this:

SELECT *
FROM   a, b, c
WHERE  a.id = b.id
AND    b.id = c.id
AND    c.id = a.id

are the really any advantages to this? Surely the optimiser can imply this for itself?

edit: I know it's evil syntax, but it's a quick and dirty example of legitimate legacy code +1 @Stu for cleaning it up

Was it helpful?

Solution

You don't need to do this in todays database engines, but there was a time when things like that would give the query optimizer more hints as to possible index paths and thus to speedier results.

These days that entire syntax is going out anyway.

OTHER TIPS

This is filthy, evil legacy syntax. You write this as

Select
  *  -- Oh, and don't ever use *, either
From
  A 
  Inner Join B On A.ID = B.ID
  Inner Join C On B.ID = C.ID

No this syntax stems from the days before joins were in the language. Not sure of the problems associated with it, but there are definitely language constructs that are more supported for jointing tables.

I just want to say that this kind of joining is the devils work.
Just think about it; the conditions for joining and filtering gets mixed together in the where statement.
What happens when you need to join across 20 tables and filter on 15 values?

Again, just my $.02

In Microsoft SQL the query plans for these two queries are identical - they are executed in the same way.

If you look at it from a mathematical point of view, your examples should yield the same results.

a = b = c

So your first example would yield the same results as the second, so no need to do the extra work.

This question is similar to this one here with a very in-depth explanation:

SQL question from Joel Spolsky article

The short answer is, that the explicit declaration of the transitiv property may speed the query up. This is because query optimization is not a trivial task and some SQL servers might have problems with it.

That syntax has its uses though ... there are times when you find you need to join two tables on more than one field

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top