CYBERTEC PostgreSQL Logo

Outer joins revisited

08.2012 / Category: / Tags: |

Some time ago I wrote about joins and especially about outer joins. However, people repeatedly make the same errors over and over again, so I thought that it might be worth it to address the topic again - maybe I can rescue some souls and prevent some bugs.

Basic example for outer joins

We can populate the tables nicely:

The most simplistic case is a normal inner join. This is not going to cause any
surprises to most users:

The differences

People often ask if the way the join is written will make any difference:

There is absolutely no difference between an explicit and an implicit join. It
is simply a matter of style but it has no impact on the way the planner works
(unless you exceed join_collapse_limit).

Inner joins vs. outer joins

Inner joins should be a pretty common thing. Outer joins cause a lot more problems. Here is a simple case:

Caution!

The situation starts to be tricky if you start to add filters to the query. People might expect to reduce the number of rows by a filter like that but this is NOT the case - keep in mind: A filter in the ON-clause WILL NOT reduce the number of rows on either side of the join. This is not a bug - this is totally desired and logical behavior:

Most people would think that we should get just one row instead of three BUT all
we do is to limit the data which PostgreSQL will use to find common rows.

If you want to filter data - use a WHERE-clause instead:

Please think twice when you are writing outer joins - otherwise your results
will simply be plain wrong.

Related blog topics:
Enforcing join orders in PostgreSQL
Time in PostgreSQL: Outer joins

Leave a Reply

Your email address will not be published. Required fields are marked *

CYBERTEC Logo white
Get the newest PostgreSQL Info & Tools


    This site is protected by reCAPTCHA and the Google Privacy Policy & Terms of Service apply.

    ©
    2024
    CYBERTEC PostgreSQL International GmbH
    phone-handsetmagnifiercrosscross-circle
    linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram