How do constant values effect the ON clause of Joins?

Jude Allred picture Jude Allred · Oct 8, 2009 · Viewed 15.1k times · Source

I've recently discovered that the ON clause of a LEFT JOIN may contain values such as (1 = 1).

This is upsetting to me, as it breaks my perception of how joins function.

I've encountered a more elaborate version of the following situation:

SELECT DISTINCT Person.ID, ...
FROM Person LEFT JOIN Manager 
ON (Manager.ID = Person.ID OR Manager.ID = -1))
WHERE (...)

It's perfectly legal. What does "Manager.ID = -1" accomplish, if anything? How can this effect the Join?

Answer

JCasso picture JCasso · Oct 8, 2009

If person table is:

id  name

1   Person One
2   Person Two
3   Person Three
4   Person Four
5   Person Five

If manager table is

id  name
-1  Admin
2   Manager One
3   Manager Two

if the query is:

SELECT DISTINCT *
FROM Person LEFT JOIN Manager 
ON (Manager.id = Person.id OR Manager.id = -1)

Then the result is:

Person One  -1  Admin
Person Two  -1  Admin
Person Two  2   Manager One
Person Three    -1  Admin
Person Three    3   Manager Two
Person Four -1  Admin
Person Five -1  Admin

Here all person rows joins with the -1 Admin (on manager table) AND if the same id exist in manager table one more join occurs.