Outer join – where do I put the (+)?

I can never remember where to put the (+) symbols in an Oracle SQL query to make it have an outer join. I rarely need to write a query with an outer join and when I do I have to build myself a test case to remember how it works. I did this just today so I thought I’d blog it.

So, I setup two tables with one matching row and one non-matching. They have one column x which I will join on.

So, when I see this I think about the real query I’m building and I ask myself “which table gets the (+)?” So, I think that the side with the (+) is the side that doesn’t have to match. In the first case table b only matches where x=1 but you see both of a’s records x=1 and 2. The second query reverses it. Or, another way to say this is that the side of the equals sign without the outer join symbol has all of its rows returned and the other side only has the matching rows.

The other thing that confuses me is constants. Do we need the outer join symbol with a where clause condition on a constant, i.e. on a condition that doesn’t join the two tables?

I would think that the first query would return the same results as the second but it doesn’t. I guess the meaning of the first query is that you only return rows where a.x=2. The column a.x is null on the row where a doesn’t match b. The a row that does match b has a.x=1. No neither null or 1 equals 2 so you get no rows returned.

The second query is weird because a is null for both of b’s values of x. But I think the way this works is that the condition a.x=2 is first applied leaving a with no rows. Then both rows in b are treated as non-matching so a.x is null. So, maybe it is safe to say that without the (+) the condition is applied after the join and with (+) the condition is applied before it.

Not very profound but at least having this on my blog will be something I can refer to a month from now when I need this again.

– Bobby

Share this:

About Bobby

I live in Chandler, Arizona with my wife and three daughters. I work for US Foods, the second largest food distribution company in the United States. I've been working as an Oracle database administrator and PeopleSoft administrator since 1994. I'm very interested in Oracle performance tuning.

Pretty cool. I vaguely remember that there is more you can do with the ANSI syntax than the old (+) way but I’ve forgotten the details. This seems like a good example – using a function in the outer join condition. I know I should abandon the old syntax but I’ve been resisting.