Explain JOIN vs. LEFT JOIN and WHERE condition performance suggestion in more detail

Effectively, WHERE conditions and JOIN conditions for [INNER] JOIN are 100 % equivalent in PostgreSQL. (It’s good practice to use explicit JOIN conditions to make queries easier to read and maintain, though).

The same is not true for a LEFT JOIN combined with a WHERE condition on a table to the right of the join. The purpose of a LEFT JOIN is to preserve all rows on the left side of the join, irregardless of a match on the right side. If no match is found, the row is extended with NULL values for columns on the right side. The manual:

LEFT OUTER JOIN

First, an inner join is performed. Then, for each row in T1 that does not satisfy the join condition with any row in T2, a joined row
is added with null values in columns of T2. Thus, the joined table
always has at least one row for each row in T1.

If you then apply a WHERE condition that requires something else than a NULL value on columns of tables on the right side, you void the effect and forcibly convert the LEFT [OUTER] JOIN to work like a plain [INNER] JOIN, just (possibly) more expensively due to a more complicated query plan.

In a query with many joined tables, Postgres (or any RDBMS) is hard put to it to find the best (or even a good) query plan. The number of theoretically possible sequences to join tables grows factorially (!). Postgres uses the “Generic Query Optimizer” for the task and there are some settings to influence it.

Obfuscating the query with misleading LEFT JOIN as outlined, makes the work of the query planner harder, is misleading for human readers and typically hints at errors in the query logic.

Related answers for problems stemming from this:

  • Why does null equal integer in WHERE?
  • Query with LEFT JOIN not returning rows for count of 0
  • SQL query using outer join and limiting child records for each parent
  • Left outer join acting like inner join
  • Select rows which are not present in other table

Etc.

Leave a Comment

tech