Difference between "on .. and" and "on .. where" in SQL Left Join?

20    Asked by JonathanSkinner in SQL Server , Asked on May 12, 2025

What is the difference between using "ON" and "WHERE" in a SQL LEFT JOIN? Learn how the placement of conditions affects the results, with "ON" filtering rows during the join process and "WHERE" filtering after the join has occurred.

Answered by John Ingerson

In SQL, when performing a LEFT JOIN, the placement of conditions using ON and WHERE can lead to different results. Understanding the distinction between them is crucial for accurate query outcomes.

 Using ON in a LEFT JOIN:

  • The ON clause defines the condition for the join. It is used to match rows between the two tables.
  • In the case of a LEFT JOIN, this condition determines how the rows from the left table will be matched to rows in the right table. If there is no match, the result will still include rows from the left table with NULL values for columns from the right table.

Example:

SELECT a.name, b.order_date
FROM customers a
LEFT JOIN orders b ON a.customer_id = b.customer_id;

This query keeps all customers, even if they don't have an order. The ON condition controls how the rows are matched.

 Using WHERE in a LEFT JOIN:

  • The WHERE clause filters the results after the join has been applied.
  • If you apply a condition that references the right table in the WHERE clause, you may inadvertently turn the LEFT JOIN into an INNER JOIN, as it will exclude rows where the right table's columns are NULL.

Example:

SELECT a.name, b.order_date
FROM customers a
LEFT JOIN orders b ON a.customer_id = b.customer_id
WHERE b.order_date IS NOT NULL;

This query will only return customers who have placed an order, essentially removing the "LEFT JOIN" effect because of the filter in the WHERE clause.

 Key Differences:

  • ON: Defines the join condition and works before filtering.
  • WHERE: Filters the results after the join is made, potentially removing rows with NULL values from the right table in a LEFT JOIN.

Knowing where to place your conditions can help you control the results and prevent unintended exclusions in your queries!



Your Answer

Interviews

Parent Categories