Why MySQL's LEFT JOIN is returning "NULL" records when with WHERE clause? Why MySQL's LEFT JOIN is returning "NULL" records when with WHERE clause? php php

Why MySQL's LEFT JOIN is returning "NULL" records when with WHERE clause?


A left join condition and where condition filter are not both same. Data is filtered by the where clause after the physical join is done. if you look a left join it will normally return every row from your left table, but once you have a where clause, it will filter the output of the join so the result is like an inner join. You will want to focus on the two diagrams on the left side of the image below.

enter image description here


The solution to this question becomes quite intuitive once one is aware of the execution order or Logical Query Processing Phases of the SQL statement. The order is: -

1. FROM2. ON3. OUTER4. WHERE5. GROUP BY6. CUBE | ROLLUP7. HAVING8. SELECT9. DISTINCT10. ORDER BY11. TOP

As ON is performed before the OUTER(LEFT/RIGHT) part(adding NULL valued rows) of the JOIN, the 1st case has rows with NULL values in rank column.In the 2nd case the rows get filtered out based on the values of the rank column after the OUTER JOIN(LEFT JOIN here) is performed. Hence, the rows with NULL values in the rank column are filtered out.

One very important thing that can be noticed in your SQL query is the comparison with NULLThis area requires special attention as the NULL values when with NULL/NON-NULL values using the normal arithmetic operators result NULL(it is neither TRUE nor FALSE) because NULL means no value is available for comparison. This behavior is defined in the ANSI SQL-92 standard.(This can be overridden by turning ansi null(actual name may vary) parameter off in some SQL processors)So, your SQL query with where clause filters out rows with NULL value in rank column which might seem counter-intuitive due to "17 != NULL" seems TRUEex-

NULL = NULL results NULL/UNKNOWN

17 = NULL results NULL/UNKNOWN

17 != NULL results NULL?UNKNOWN

Some interesting posts/blogs for reference are:

http://blog.sqlauthority.com/2009/04/06/sql-server-logical-query-processing-phases-order-of-statement-execution/http://blog.sqlauthority.com/2009/03/15/sql-server-interesting-observation-of-on-clause-on-left-join-how-on-clause-effects-resultset-in-left-join/http://www.xaprb.com/blog/2006/05/18/why-null-never-compares-false-to-anything-in-sql/


First Case :

After joining, the records are getting filtered by the (WHERE clause). So only 1 result.

Second Case (when you replace WHERE with AND)

Will return all join entries + entries satisfied in second condition (t2.rank != 17). That is why here you get 2 records ( one from join + another from AND clause)