Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL JOIN - WHERE clause vs. ON clause

After reading it, this is not a duplicate of Explicit vs Implicit SQL Joins. The answer may be related (or even the same) but the question is different.


What is the difference and what should go in each?

If I understand the theory correctly, the query optimizer should be able to use both interchangeably.

like image 931
BCS Avatar asked Dec 09 '08 20:12

BCS


People also ask

WHERE VS on in SQL join?

Is there a difference between the WHERE and ON clause? Yes. ON should be used to define the join condition and WHERE should be used to filter the data.

Can we use WHERE clause with joins?

You join two tables by creating a relationship in the WHERE clause between at least one column from one table and at least one column from another. The join creates a temporary composite table where each pair of rows (one from each table) that satisfies the join condition is linked to form a single row.

What is difference between on and using join clause?

The difference between using clause and on clause is: while joining two or more tables by using “using clause”, column name of both table must same via using which table is being joined whereas in case of “on clause” column name may differ.

Is it better to filter in join or WHERE clause?

In terms of readability though, especially in complex queries that have multiple joins, it is easier to spot join conditions when they are placed in the ON clause and filter conditions when they are placed in the WHERE clause.


1 Answers

They are not the same thing.

Consider these queries:

SELECT * FROM Orders LEFT JOIN OrderLines ON OrderLines.OrderID=Orders.ID WHERE Orders.ID = 12345 

and

SELECT * FROM Orders LEFT JOIN OrderLines ON OrderLines.OrderID=Orders.ID      AND Orders.ID = 12345 

The first will return an order and its lines, if any, for order number 12345. The second will return all orders, but only order 12345 will have any lines associated with it.

With an INNER JOIN, the clauses are effectively equivalent. However, just because they are functionally the same, in that they produce the same results, does not mean the two kinds of clauses have the same semantic meaning.

like image 117
Joel Coehoorn Avatar answered Oct 07 '22 01:10

Joel Coehoorn